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 node_modules
app/node_modules app/node_modules
app/.svelte-kit app/.svelte-kit
app/build app/build
.git .git
pocketbase/pb_data pocketbase/pb_data

View file

@ -1,2 +1,2 @@
PUBLIC_POCKETBASE_URL=http://localhost:8090 PUBLIC_POCKETBASE_URL=http://localhost:8090
POCKETBASE_INTERNAL_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 # Massage Studio Website CMS — Agent Guidelines
## Stack ## Stack
- **SvelteKit 2** (SSR, Svelte 5 runes mode) — all `.svelte` files use `$state`, `$derived`, `$props()` etc. - **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. - **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. - **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`. - **Docker Compose** — three services: `app` (SvelteKit), `pocketbase`, and `caddy` (reverse proxy).
## Project Structure ## Project Structure
``` ```
app/ # SvelteKit application app/ # SvelteKit application
├── src/ ├── src/
│ ├── lib/ │ ├── lib/
│ │ ├── admin/ # Admin UI components (BlockList, editors) │ │ ├── admin/ # Admin UI components (BlockList, editors)
│ │ ├── blocks/ # Public block renderers (one per BlockType) │ │ ├── blocks/ # Public block renderers (one per BlockType)
│ │ ├── components/ # Header.svelte, Footer.svelte │ │ ├── components/ # Header.svelte, Footer.svelte
│ │ ├── pb.ts # PocketBase client factory + helpers │ │ ├── pb.ts # PocketBase client factory + helpers
│ │ └── types.ts # ContentBlock, PageRecord, HeaderGlobal, FooterGlobal │ │ └── types.ts # ContentBlock, PageRecord, HeaderGlobal, FooterGlobal
│ ├── routes/ │ ├── routes/
│ │ ├── +layout.svelte # Root layout (admin vs public shell) │ │ ├── +layout.svelte # Root layout (admin vs public shell)
│ │ ├── +page.svelte # Home page (slug=home) │ │ ├── +page.svelte # Home page (slug=home)
│ │ ├── [slug]/ # Dynamic CMS pages │ │ ├── [slug]/ # Dynamic CMS pages
│ │ ├── admin/ # Admin area (login, pages, globals) │ │ ├── admin/ # Admin area (login, pages, globals)
│ │ └── preview/ # Draft preview via sessionStorage │ │ └── preview/ # Draft preview via sessionStorage
│ └── app.css # Tailwind + DaisyUI + custom theme │ └── app.css # Tailwind + DaisyUI + custom theme
├── static/ # Static assets ├── static/ # Static assets
├── build/ # Production build output ├── build/ # Production build output
├── svelte.config.js # Adapter-node, runes mode forced ├── svelte.config.js # Adapter-node, runes mode forced
├── vite.config.ts # Tailwind v4 + SvelteKit plugins ├── vite.config.ts # Tailwind v4 + SvelteKit plugins
└── package.json └── package.json
pocketbase/pb_data/ # PocketBase data (mounted volume-mounted) pocketbase/pb_data/ # PocketBase data (mounted volume-mounted)
docker-compose.yml # app + pocketbase services docker-compose.yml # app + pocketbase services
Dockerfile # Multi-stage Node 22 build Dockerfile # Multi-stage Node 22 build
``` ```
## Key Conventions ## Key Conventions
### Svelte 5 Runes Mode ### Svelte 5 Runes Mode
All components use Svelte 5 runes syntax — **never** `export let`, `$:`, or `on:click`. Use: All components use Svelte 5 runes syntax — **never** `export let`, `$:`, or `on:click`. Use:
- `$props()` for component props - `$props()` for component props
- `$state()` for reactive local state - `$state()` for reactive local state
- `$derived()` for computed values - `$derived()` for computed values
- `$effect()` / `onMount` for side effects - `$effect()` / `onMount` for side effects
- `{@render children()}` for slots - `{@render children()}` for slots
- `onclick={handler}` (not `on:click`) - `onclick={handler}` (not `on:click`)
### Block System ### Block System
Pages are composed of `ContentBlock[]`. Each block has `{ id, type, data }`. Block types are defined in `$lib/types.ts`: 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` `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`. - **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 - **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 - **Defaults**: `$lib/admin/blockDefaults.ts` — `createBlock(type)` generates a new block with sensible defaults
- **Block list**: `$lib/admin/BlockList.svelte` — draggable reorder, select, delete - **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`. 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 ### PocketBase Integration
- Client created in `hooks.server.ts` (`event.locals.pb`) — injected per-request with auth cookie - Client created in `hooks.server.ts` (`event.locals.pb`) — injected per-request with auth cookie
- `$lib/pb.ts` exports `createPocketBase()`, `getFileUrl()`, `uploadMedia()` - `$lib/pb.ts` exports `createPocketBase()`, `getFileUrl()`, `uploadMedia()`
- Collections: `pages` (slug, title, blocks[], published), `globals` (key, data), `media` (file, alt) - Collections: `pages` (slug, title, blocks[], published), `globals` (key, data), `media` (file, alt)
- Server load functions use `locals.pb.collection('pages').getFirstListItem()` - Server load functions use `locals.pb.collection('pages').getFirstListItem()`
### Styling ### Styling
- **Public site**: Custom theme via `@theme` in `app.css` — colors: `warm`, `charcoal`, `sage`, `sage-dark`, `terracotta`. Fonts: `DM Sans` (body), `Playfair Display` (headings). - **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.) - **Admin area**: DaisyUI utility classes (`btn`, `card`, `input`, `select`, `rounded-box`, etc.)
- **Prose**: `.prose-wellness` class for rich text content styling - **Prose**: `.prose-wellness` class for rich text content styling
### Routing ### Routing
- `+layout.server.ts` fetches header/footer globals for every public page - `+layout.server.ts` fetches header/footer globals for every public page
- `+page.server.ts` for home fetches `slug = "home" && published = true` - `+page.server.ts` for home fetches `slug = "home" && published = true`
- `[slug]/+page.server.ts` fetches by dynamic slug - `[slug]/+page.server.ts` fetches by dynamic slug
- Admin routes protected in `hooks.server.ts` — redirects to `/admin/login` if unauthenticated - Admin routes protected in `hooks.server.ts` — redirects to `/admin/login` if unauthenticated
## Build & Dev Commands ## Build & Dev Commands
```sh ```sh
# Development (from app/) # Development (from app/)
cd app cd app
npm install npm install
npm run dev # http://localhost:5173 npm run dev # http://localhost:5173
# Production build # Production build
npm run build npm run build
# Type checking # Type checking
npm run check npm run check
# Docker full stack # Docker full stack (single entry point on port 8080)
docker compose up --build docker compose up --build
# App: http://localhost:3000 # App + PocketBase via Caddy: http://localhost:8080
# PocketBase admin: http://localhost:8090/_/ # PocketBase admin: http://localhost:8080/_/
# PocketBase only (for local dev) # PocketBase only (for local dev outside Docker)
docker compose up pocketbase docker compose up pocketbase
``` # Direct access: http://localhost:8090/_/
```
## Environment
## Environment
- `PUBLIC_POCKETBASE_URL` — public-facing PocketBase URL (default `http://localhost:8090`)
- `POCKETBASE_INTERNAL_URL` — internal Docker network URL (`http://pocketbase:80`) - `PUBLIC_POCKETBASE_URL` — public-facing PocketBase URL, now accessed through the Caddy reverse proxy (default `http://localhost:8080`)
- `ORIGIN` — SvelteKit origin for SSR (`http://localhost:3000`) - `POCKETBASE_INTERNAL_URL` — internal Docker network URL (`http://pocketbase:80`)
- Copy `app/.env.example` → `app/.env` for local dev - `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 # SOFTWARE DEVELOPMENT AGREEMENT
This Software Development Agreement ("Agreement") is entered into on [DATE] This Software Development Agreement ("Agreement") is entered into on [DATE]
between between
**Developer:** **Developer:**
[YOUR NAME] [YOUR NAME]
[ADDRESS] [ADDRESS]
[IČO / REGISTRATION NUMBER, IF APPLICABLE] [IČO / REGISTRATION NUMBER, IF APPLICABLE]
Email: [EMAIL] Email: [EMAIL]
and and
**Client:** **Client:**
[CLIENT NAME] [CLIENT NAME]
[CLIENT ADDRESS] [CLIENT ADDRESS]
Email: [EMAIL] Email: [EMAIL]
--- ---
## 1. Subject of the Agreement ## 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 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: 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, - 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, - 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 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 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, - 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, - Stripe integration for online payment processing,
- booking confirmations and notifications for both the Client and end customers, - booking confirmations and notifications for both the Client and end customers,
- integration with Client's google calendar - integration with Client's google calendar
- buffer time and minimum lead time configuration per service, - buffer time and minimum lead time configuration per service,
- co-worker profiles with direct contact information (no online booking required for co-workers), - 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, - deployment and configuration of hosting infrastructure under the Client's ownership,
- migration of existing content necessary for operation of the website. - 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. 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 ## 2. Project Duration
The estimated duration of the project is five (5) months from the Effective Date of this Agreement. 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). 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. 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 ## 3. Compensation
The total project fee shall be: The total project fee shall be:
**EUR 2,500** **EUR 2,500**
The Client shall pay the fee in five monthly installments of: The Client shall pay the fee in five monthly installments of:
**EUR 500 per month** **EUR 500 per month**
Invoices shall be due within fourteen (14) days of issuance. 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. 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. 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. Any suspension caused by late payment shall automatically extend project deadlines by the duration of the suspension.
--- ---
## 4. Hosting ## 4. Hosting
Hosting services, domain registrations, and third-party services shall be registered and owned by the Client. 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 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. The Client shall be solely responsible for all fees charged by hosting providers, registrars, and third-party service providers.
--- ---
## 5. Intellectual Property ## 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. 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 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 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. The Developer retains the right to use, improve, and build commercial products from the CMS platform independently of this project.
--- ---
## 6. Content Management ## 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: 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 co-worker profiles,
- adding, editing, deleting and hiding services and pricing, - adding, editing, deleting and hiding services and pricing,
- adding, editing, deleting and managing events, workshops and courses in the calendar, - adding, editing, deleting and managing events, workshops and courses in the calendar,
- creating new pages using the block-based page builder. - creating new pages using the block-based page builder.
The following tasks will typically require developer involvement: The following tasks will typically require developer involvement:
- new third-party integrations, - new third-party integrations,
- structural or architectural changes to the website, - structural or architectural changes to the website,
- new features or functionality outside the current scope, - new features or functionality outside the current scope,
- custom development beyond standard CMS capabilities. - 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. Future developer assistance will be available at an agreed hourly rate or fixed price per task, as discussed separately.
--- ---
## 7. Change Requests ## 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. 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 ## 8. Client Cooperation
The Client agrees to provide all necessary information, materials, approvals, and feedback required for completion of the project. 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: 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, - 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 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. 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. Communication by email or WhatsApp shall be considered sufficient for all approvals, feedback, and project-related decisions.
--- ---
## 9. Acceptance ## 9. Acceptance
The Client shall review delivered work within fourteen (14) days after delivery. 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. If no substantial objections are communicated within that period, the delivered work shall be deemed accepted.
--- ---
## 10. Termination ## 10. Termination
Either party may terminate this Agreement by written notice. 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. 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. Any payments already made are non-refundable for work already performed.
--- ---
## 11. Limitation of Liability ## 11. Limitation of Liability
The Developer shall not be liable for: The Developer shall not be liable for:
- downtime caused by third-party providers, - downtime caused by third-party providers,
- hosting provider failures, - hosting provider failures,
- domain registrar failures, - domain registrar failures,
- third-party software or service outages, - third-party software or service outages,
- indirect or consequential damages. - 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. 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 ## 12. Governing Law and Jurisdiction
This Agreement shall be governed by and construed in accordance with the laws of the Czech Republic. 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. 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 ## 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. 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. Any amendments must be made in writing and agreed by both parties.
--- ---
## 14. Data Protection ## 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. 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** **Developer**
Name: __________________________ Name: __________________________
Signature: ______________________ Signature: ______________________
Date: ___________________________ Date: ___________________________
--- ---
**Client** **Client**
Name: __________________________ Name: __________________________
Signature: ______________________ Signature: ______________________
Date: ___________________________ 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 # syntax=docker/dockerfile:1.7
FROM node:22-alpine AS build FROM node:22-alpine AS build
WORKDIR /app WORKDIR /app
ENV NPM_CONFIG_AUDIT=false \ ENV NPM_CONFIG_AUDIT=false \
NPM_CONFIG_FUND=false \ NPM_CONFIG_FUND=false \
NPM_CONFIG_PROGRESS=false NPM_CONFIG_PROGRESS=false
COPY app/package*.json ./ COPY app/package*.json ./
RUN --mount=type=cache,target=/root/.npm npm ci --ignore-scripts --no-audit --no-fund RUN --mount=type=cache,target=/root/.npm npm ci --ignore-scripts --no-audit --no-fund
COPY app/ ./ COPY app/ ./
RUN npm run build RUN npm run build
FROM node:22-alpine FROM node:22-alpine
WORKDIR /app WORKDIR /app
ENV NODE_ENV=production \ ENV NODE_ENV=production \
NPM_CONFIG_AUDIT=false \ NPM_CONFIG_AUDIT=false \
NPM_CONFIG_FUND=false \ NPM_CONFIG_FUND=false \
NPM_CONFIG_PROGRESS=false NPM_CONFIG_PROGRESS=false
COPY --from=build /app/build ./build COPY --from=build /app/build ./build
COPY --from=build /app/package*.json ./ COPY --from=build /app/package*.json ./
RUN --mount=type=cache,target=/root/.npm npm ci --omit=dev --ignore-scripts --no-audit --no-fund RUN --mount=type=cache,target=/root/.npm npm ci --omit=dev --ignore-scripts --no-audit --no-fund
EXPOSE 3000 EXPOSE 3000
CMD ["node", "build"] CMD ["node", "build"]

227
README.md
View file

@ -1,112 +1,115 @@
# Massage Studio Website CMS # 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. 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 ## Stack
- SvelteKit + SSR - SvelteKit + SSR
- PocketBase REST API via the `pocketbase` SDK - PocketBase REST API via the `pocketbase` SDK
- Tailwind CSS v4 + DaisyUI - Tailwind CSS v4 + DaisyUI
- Docker Compose with two services: `app` and `pocketbase` - Docker Compose with three services: `app`, `pocketbase`, and `caddy` (reverse proxy)
## Local development ## Local development
1. Install Node.js `22.x` or another version accepted by SvelteKit's Vite plugin. 1. Install Node.js `22.x` or another version accepted by SvelteKit's Vite plugin.
2. Copy the app env file: 2. Copy the app env file:
```sh ```sh
cp app/.env.example app/.env cp app/.env.example app/.env
``` ```
3. Start PocketBase on port `8090`. With Docker: 3. Start PocketBase on port `8090`. With Docker:
```sh ```sh
docker compose up pocketbase docker compose up pocketbase
``` ```
4. In another terminal: 4. In another terminal:
```sh ```sh
cd app cd app
npm install npm install
npm run dev npm run dev
``` ```
5. Visit `http://localhost:5173`. 5. Visit `http://localhost:5173`.
## Docker Compose > **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`.
Run the full stack: ## Docker Compose
```sh Run the full stack:
docker compose up --build
``` ```sh
docker compose up --build
If dependency installation is slow on the first build, enable BuildKit explicitly: ```
```sh If dependency installation is slow on the first build, enable BuildKit explicitly:
DOCKER_BUILDKIT=1 docker compose build --progress=plain app
docker compose up ```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` Subsequent builds reuse the npm cache declared in the `Dockerfile`.
- PocketBase admin UI: `http://localhost:8090/_/`
- Single entry point (Caddy reverse proxy): **`http://localhost:8080`**
The app container uses two PocketBase URLs: - SvelteKit app: `http://localhost:8080/` (or any non-API path)
- PocketBase admin UI: `http://localhost:8080/_/`
- `POCKETBASE_INTERNAL_URL=http://pocketbase:80` for server-side SvelteKit calls from the app container when using the included `spectado/pocketbase` image. - PocketBase REST API: `http://localhost:8080/api/`
- `PUBLIC_POCKETBASE_URL=http://localhost:8090` for browser-side admin uploads and public file URLs during local Docker development. - PocketBase direct access (internal only, not exposed): `http://localhost:8090`
In production, set `PUBLIC_POCKETBASE_URL` to the browser-accessible PocketBase URL, or to the reverse-proxied PocketBase path/origin you expose publicly. The app container uses two PocketBase URLs:
## PocketBase setup - `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.
1. Open `http://localhost:8090/_/`.
2. Create the first PocketBase admin user when prompted. ## PocketBase setup
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: 1. Open `http://localhost:8080/_/` (or `http://localhost:8090/_/` for direct access).
- `pages`: slug `home`, title `Home`, `published: true`, and a blocks JSON array. 2. Create the first PocketBase admin user when prompted.
- `globals`: key `header`, data matching the header JSON in the project prompt. 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.
- `globals`: key `footer`, data matching the footer JSON in the project prompt. 4. Create starter records:
- `pages`: slug `home`, title `Home`, `published: true`, and a blocks JSON array.
If the `globals` records do not exist, the app falls back to safe defaults and the admin globals page will create them. - `globals`: key `header`, data matching the header JSON in the project prompt.
- `globals`: key `footer`, data matching the footer JSON in the project prompt.
### Manual collection fields fallback
If the `globals` records do not exist, the app falls back to safe defaults and the admin globals page will create them.
If schema import fails because of a PocketBase version mismatch, create these collections manually:
### Manual collection fields fallback
- `pages`
- `slug`: text, required, unique If schema import fails because of a PocketBase version mismatch, create these collections manually:
- `title`: text, required
- `blocks`: json - `pages`
- `published`: bool - `slug`: text, required, unique
- `globals` - `title`: text, required
- `key`: text, required, unique - `blocks`: json
- `data`: json - `published`: bool
- `media` - `globals`
- `file`: file, required, max select `1`, image mime types - `key`: text, required, unique
- `alt`: text - `data`: json
- `media`
## Authentication - `file`: file, required, max select `1`, image mime types
- `alt`: text
Admin routes live under `/admin`. Login accepts either:
## Authentication
- a PocketBase admin account, or
- a record from a `users` auth collection if you create one. Admin routes live under `/admin`. Login accepts either:
All `/admin` routes except `/admin/login` are guarded in `src/hooks.server.ts`. - a PocketBase admin account, or
- a record from a `users` auth collection if you create one.
## CMS routes
All `/admin` routes except `/admin/login` are guarded in `src/hooks.server.ts`.
- `/admin/login` — sign in
- `/admin/pages` — list/create pages ## CMS routes
- `/admin/pages/[slug]` — block editor with draft preview
- `/admin/globals` — header/footer editor - `/admin/login` — sign in
- `/admin/pages` — list/create pages
## Public routes - `/admin/pages/[slug]` — block editor with draft preview
- `/admin/globals` — header/footer editor
- `/` renders `pages.slug = "home"`
- `/[slug]` renders any other published page ## Public routes
- Unpublished pages return `404`
- `/` renders `pages.slug = "home"`
## Notes - `/[slug]` renders any other published page
- Unpublished pages return `404`
- 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. ## Notes
- 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.
- 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 url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=Playfair+Display:wght@600;700&display=swap');
@import 'tailwindcss'; @import 'tailwindcss';
@plugin 'daisyui' { @plugin 'daisyui' {
themes: light --default; themes: light --default;
} }
@theme { @theme {
--font-sans: 'DM Sans', ui-sans-serif, system-ui, sans-serif; --font-sans: 'DM Sans', ui-sans-serif, system-ui, sans-serif;
--font-serif: 'Playfair Display', Georgia, serif; --font-serif: 'Playfair Display', Georgia, serif;
--color-warm: var(--color-bg, #faf8f5); --color-warm: var(--color-bg, #faf8f5);
--color-charcoal: var(--color-heading, #2c2c2c); --color-charcoal: var(--color-heading, #2c2c2c);
--color-sage: var(--color-primary, #8a9a7b); --color-sage: var(--color-primary, #8a9a7b);
--color-sage-dark: color-mix(in srgb, var(--color-primary, #8a9a7b) 80%, #000); --color-sage-dark: color-mix(in srgb, var(--color-primary, #8a9a7b) 80%, #000);
--color-terracotta: var(--color-accent, #c9825f); --color-terracotta: var(--color-accent, #c9825f);
} }
@keyframes shrink { @keyframes shrink {
from { scale: 0 1; } from { scale: 0 1; }
to { scale: 1 1; } to { scale: 1 1; }
} }
.delete-fill { .delete-fill {
position: absolute; position: absolute;
inset: 0; inset: 0;
background: transparent; background: transparent;
transform-origin: left; transform-origin: left;
} }
.delete-fill.animating { .delete-fill.animating {
animation: shrink 1s ease-in-out forwards; animation: shrink 1s ease-in-out forwards;
background: var(--error, #f43f5e); background: var(--error, #f43f5e);
} }
.btn.delete-holding { .btn.delete-holding {
color: white !important; color: white !important;
} }
.btn.delete-holding .text-error { .btn.delete-holding .text-error {
color: white !important; color: white !important;
} }
:root { :root {
--fg-heading: var(--color-heading, #2c2c2c); --fg-heading: var(--color-heading, #2c2c2c);
--fg-subheading: var(--color-subheading, #4a4a4a); --fg-subheading: var(--color-subheading, #4a4a4a);
--fg-body: var(--color-text, #2c2c2c); --fg-body: var(--color-text, #2c2c2c);
background: var(--color-bg, #faf8f5); background: var(--color-bg, #faf8f5);
color: var(--fg-body); color: var(--fg-body);
font-family: 'DM Sans', ui-sans-serif, system-ui, sans-serif; font-family: 'DM Sans', ui-sans-serif, system-ui, sans-serif;
} }
/* ── Foreground colour utilities (set per-block via BackgroundWrapper) ── */ /* ── Foreground colour utilities (set per-block via BackgroundWrapper) ── */
.text-fg-body { color: var(--fg-body, #2c2c2c); } .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\/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\/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\/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\/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-body\/60 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 60%, transparent); }
.text-fg-heading { color: var(--fg-heading, #2c2c2c); } .text-fg-heading { color: var(--fg-heading, #2c2c2c); }
.text-fg-subheading { color: var(--fg-subheading, #4a4a4a); } .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\/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\/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\/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\/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); } .text-fg-subheading\/60 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 60%, transparent); }
body { body {
min-height: 100vh; min-height: 100vh;
margin: 0; margin: 0;
background: background:
radial-gradient(circle at top left, rgba(var(--color-accent-rgb, 201, 130, 95), 0.1), transparent 36rem), radial-gradient(circle at top left, rgba(var(--color-accent-rgb, 201, 130, 95), 0.1), transparent 36rem),
var(--color-bg, #faf8f5); var(--color-bg, #faf8f5);
} }
h1, h1,
h2, h2,
h3, h3,
h4 { h4 {
font-family: 'Playfair Display', Georgia, serif; font-family: 'Playfair Display', Georgia, serif;
color: var(--fg-heading, #2c2c2c); color: var(--fg-heading, #2c2c2c);
} }
.prose-wellness p { .prose-wellness p {
margin: 0.75rem 0; margin: 0.75rem 0;
line-height: 1.8; line-height: 1.8;
} }
.prose-wellness h2 { .prose-wellness h2 {
margin: 1.25rem 0 0.5rem; margin: 1.25rem 0 0.5rem;
font-size: clamp(2rem, 4vw, 3.25rem); font-size: clamp(2rem, 4vw, 3.25rem);
line-height: 1.05; line-height: 1.05;
} }
.prose-wellness h3 { .prose-wellness h3 {
margin: 1rem 0 0.5rem; margin: 1rem 0 0.5rem;
font-size: 1.6rem; font-size: 1.6rem;
} }
.prose-wellness ul { .prose-wellness ul {
list-style: disc; list-style: disc;
padding-left: 1.5rem; padding-left: 1.5rem;
} }
.prose-wellness a { .prose-wellness a {
color: color-mix(in srgb, var(--color-primary, #8a9a7b) 90%, #000); color: color-mix(in srgb, var(--color-primary, #8a9a7b) 90%, #000);
text-decoration: underline; text-decoration: underline;
text-underline-offset: 3px; text-underline-offset: 3px;
} }
/* ── Scroll-reveal animations ── */ /* ── Scroll-reveal animations ── */
.reveal { .reveal {
opacity: 0; opacity: 0;
transform: translateY(30px); transform: translateY(30px);
transition: transition:
opacity 0.7s cubic-bezier(0.25, 0.1, 0.25, 1), opacity 0.7s cubic-bezier(0.25, 0.1, 0.25, 1),
transform 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 { .reveal-visible {
opacity: 1; opacity: 1;
transform: translateY(0); transform: translateY(0);
} }
/* ── Hero fade-in stagger ── */ /* ── Hero fade-in stagger ── */
.animate-fade-in { .animate-fade-in {
opacity: 0; opacity: 0;
transform: translateY(20px); transform: translateY(20px);
animation: fadeInUp 0.8s cubic-bezier(0.25, 0.1, 0.25, 1) forwards; animation: fadeInUp 0.8s cubic-bezier(0.25, 0.1, 0.25, 1) forwards;
} }
@keyframes fadeInUp { @keyframes fadeInUp {
to { to {
opacity: 1; opacity: 1;
transform: translateY(0); transform: translateY(0);
} }
} }
/* ── Smooth scroll ── */ /* ── Smooth scroll ── */
html { html {
scroll-behavior: smooth; scroll-behavior: smooth;
} }

View file

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

View file

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

View file

@ -1,69 +1,69 @@
import { v4 as uuid } from 'uuid'; import { v4 as uuid } from 'uuid';
import type { BlockType, ContentBlock } from '$lib/types'; import type { BlockType, ContentBlock } from '$lib/types';
export const blockLabels: Record<BlockType, string> = { export const blockLabels: Record<BlockType, string> = {
text: 'Text', text: 'Text',
image_text: 'Image + Text', image_text: 'Image + Text',
timeline: 'Timeline', timeline: 'Timeline',
hero: 'Hero', hero: 'Hero',
button: 'Button', button: 'Button',
spacer: 'Spacer', spacer: 'Spacer',
testimonials: 'Testimonials', testimonials: 'Testimonials',
upcoming_calendar: 'Upcoming Calendar' upcoming_calendar: 'Upcoming Calendar'
}; };
export const blockTypes = Object.keys(blockLabels) as BlockType[]; export const blockTypes = Object.keys(blockLabels) as BlockType[];
export function createBlock(type: BlockType): ContentBlock { export function createBlock(type: BlockType): ContentBlock {
const base = { id: uuid(), type, data: {} as Record<string, any> }; const base = { id: uuid(), type, data: {} as Record<string, any> };
switch (type) { switch (type) {
case 'text': case 'text':
base.data = { content: '<h2>New text block</h2><p>Add your copy here.</p>' }; base.data = { content: '<h2>New text block</h2><p>Add your copy here.</p>' };
break; break;
case 'image_text': case 'image_text':
base.data = { url: '', alt: '', content: '<h2>Image and text</h2><p>Add content here.</p>', imagePosition: 'left' }; base.data = { url: '', alt: '', content: '<h2>Image and text</h2><p>Add content here.</p>', imagePosition: 'left' };
break; break;
case 'timeline': case 'timeline':
base.data = { items: [{ title: 'Milestone', description: 'Describe this moment.' }] }; base.data = { items: [{ title: 'Milestone', description: 'Describe this moment.' }] };
break; break;
case 'hero': case 'hero':
base.data = { base.data = {
heading: 'Holistic and Experiential Learning about Happiness', heading: 'Holistic and Experiential Learning about Happiness',
subheading: 'Individual sessions, workshops and events in Oslo', subheading: 'Individual sessions, workshops and events in Oslo',
buttonLabel: 'BOOK NOW', buttonLabel: 'BOOK NOW',
buttonUrl: '/book' buttonUrl: '/book'
}; };
break; break;
case 'button': case 'button':
base.data = { base.data = {
label: 'Learn More', label: 'Learn More',
href: '/', href: '/',
variant: 'primary', variant: 'primary',
size: 'md', size: 'md',
alignment: 'center' alignment: 'center'
}; };
break; break;
case 'spacer': case 'spacer':
base.data = { height: 64 }; base.data = { height: 64 };
break; break;
case 'testimonials': case 'testimonials':
base.data = { base.data = {
title: 'What They Say About Me', title: 'What They Say About Me',
items: [ 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: '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: '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: "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' } { 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; break;
case 'upcoming_calendar': case 'upcoming_calendar':
base.data = { base.data = {
title: 'Upcoming Events', title: 'Upcoming Events',
categories: [] categories: []
}; };
break; break;
} }
base.data._background = { type: 'none', color: '', attachment: 'scroll', overlay: false, overlayOpacity: 40 }; base.data._background = { type: 'none', color: '', attachment: 'scroll', overlay: false, overlayOpacity: 40 };
return base; return base;
} }

View file

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

View file

@ -1,105 +1,105 @@
<script lang="ts"> <script lang="ts">
import { uploadMedia } from '$lib/pb'; import { uploadMedia } from '$lib/pb';
let { url: urlProp = '', alt: altProp = '', onChange = (value: { url: string; alt: string }) => {} } = $props<{ let { url: urlProp = '', alt: altProp = '', onChange = (value: { url: string; alt: string }) => {} } = $props<{
url?: string; url?: string;
alt?: string; alt?: string;
onChange?: (value: { url: string; alt: string }) => void; onChange?: (value: { url: string; alt: string }) => void;
}>(); }>();
let uploading = $state(false); let uploading = $state(false);
let error = $state(''); let error = $state('');
let fileInput = $state<HTMLInputElement>(); let fileInput = $state<HTMLInputElement>();
// Local state synced from props so reactivity works reliably in Svelte 5 // Local state synced from props so reactivity works reliably in Svelte 5
let localUrl = $state(urlProp); let localUrl = $state(urlProp);
let localAlt = $state(altProp); let localAlt = $state(altProp);
$effect(() => { localUrl = urlProp; }); $effect(() => { localUrl = urlProp; });
$effect(() => { localAlt = altProp; }); $effect(() => { localAlt = altProp; });
function emitChange() { function emitChange() {
onChange({ url: localUrl, alt: localAlt }); onChange({ url: localUrl, alt: localAlt });
} }
async function handleFile(event: Event) { async function handleFile(event: Event) {
const file = (event.currentTarget as HTMLInputElement).files?.[0]; const file = (event.currentTarget as HTMLInputElement).files?.[0];
if (!file) return; if (!file) return;
uploading = true; uploading = true;
error = ''; error = '';
try { try {
const result = await uploadMedia(file); const result = await uploadMedia(file);
localUrl = result.url; localUrl = result.url;
emitChange(); emitChange();
} catch (e) { } catch (e) {
error = e instanceof Error ? e.message : 'Upload failed'; error = e instanceof Error ? e.message : 'Upload failed';
console.error('Image upload error:', e); console.error('Image upload error:', e);
} finally { } finally {
uploading = false; uploading = false;
} }
} }
function removeImage() { function removeImage() {
localUrl = ''; localUrl = '';
localAlt = ''; localAlt = '';
emitChange(); emitChange();
if (fileInput) fileInput.value = ''; if (fileInput) fileInput.value = '';
} }
</script> </script>
<div class="grid grid-cols-[1fr_1.5fr] gap-4"> <div class="grid grid-cols-[1fr_1.5fr] gap-4">
<!-- Drop zone / upload area --> <!-- Drop zone / upload area -->
<div <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'}" 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" role="button"
tabindex="0" tabindex="0"
onclick={() => fileInput?.click()} onclick={() => fileInput?.click()}
onkeydown={(e) => e.key === 'Enter' && fileInput?.click()} onkeydown={(e) => e.key === 'Enter' && fileInput?.click()}
> >
{#if uploading} {#if uploading}
<span class="loading loading-spinner loading-lg text-primary"></span> <span class="loading loading-spinner loading-lg text-primary"></span>
<p class="mt-3 text-sm text-base-content/60">Uploading…</p> <p class="mt-3 text-sm text-base-content/60">Uploading…</p>
{:else if localUrl} {:else if localUrl}
<div class="relative w-full"> <div class="relative w-full">
<img class="max-h-28 w-full rounded-box object-cover shadow" src={localUrl} alt={localAlt} /> <img class="max-h-28 w-full rounded-box object-cover shadow" src={localUrl} alt={localAlt} />
<button <button
class="btn btn-circle btn-error btn-outline btn-xs absolute right-1 top-1" class="btn btn-circle btn-error btn-outline btn-xs absolute right-1 top-1"
type="button" type="button"
onclick={(e) => { e.stopPropagation(); removeImage(); }} onclick={(e) => { e.stopPropagation(); removeImage(); }}
title="Remove image" title="Remove image"
>✕</button> >✕</button>
</div> </div>
{:else} {: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"> <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" /> <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> </svg>
<p class="text-center text-sm font-medium text-base-content/70">Upload image</p> <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> <p class="text-xs text-base-content/40">PNG, JPG, WebP</p>
{/if} {/if}
</div> </div>
{#if error} {#if error}
<div class="alert alert-error col-span-full text-sm">{error}</div> <div class="alert alert-error col-span-full text-sm">{error}</div>
{/if} {/if}
<input <input
class="hidden" class="hidden"
type="file" type="file"
accept="image/*" accept="image/*"
onchange={handleFile} onchange={handleFile}
disabled={uploading} disabled={uploading}
bind:this={fileInput} bind:this={fileInput}
/> />
<!-- URL & Alt fields --> <!-- URL & Alt fields -->
<div class="space-y-3"> <div class="space-y-3">
<label class="form-control w-full"> <label class="form-control w-full">
<div class="label"><span class="label-text">Image URL</span></div> <div class="label"><span class="label-text">Image URL</span></div>
<input class="input input-bordered w-full" bind:value={localUrl} oninput={() => emitChange()} /> <input class="input input-bordered w-full" bind:value={localUrl} oninput={() => emitChange()} />
</label> </label>
<label class="form-control w-full"> <label class="form-control w-full">
<div class="label"><span class="label-text">Alt text</span></div> <div class="label"><span class="label-text">Alt text</span></div>
<input class="input input-bordered w-full" bind:value={localAlt} oninput={() => emitChange()} /> <input class="input input-bordered w-full" bind:value={localAlt} oninput={() => emitChange()} />
</label> </label>
</div> </div>
</div> </div>

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,30 +1,30 @@
<script lang="ts"> <script lang="ts">
let { data } = $props<{ let { data } = $props<{
data: { data: {
heading?: string; heading?: string;
subheading?: string; subheading?: string;
buttonLabel?: string; buttonLabel?: string;
buttonUrl?: string; buttonUrl?: string;
}; };
}>(); }>();
</script> </script>
<section class="relative flex min-h-[80vh] items-center justify-center overflow-hidden px-6 py-20 md:min-h-[90vh]"> <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"> <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;"> <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'} {data.heading || 'Holistic and Experiential Learning about Happiness'}
</h1> </h1>
{#if data.subheading} {#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;"> <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} {data.subheading}
</p> </p>
{/if} {/if}
{#if data.buttonLabel} {#if data.buttonLabel}
<div class="animate-fade-in mt-10" style="animation-delay: 0.3s;"> <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'}> <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} {data.buttonLabel}
</a> </a>
</div> </div>
{/if} {/if}
</div> </div>
</section> </section>

View file

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

View file

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

View file

@ -1,87 +1,87 @@
<script lang="ts"> <script lang="ts">
let { data } = $props<{ data: Record<string, any> }>(); let { data } = $props<{ data: Record<string, any> }>();
const testimonials = data.items || [ 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: '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: '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: "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' } { 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'; const title = data.title || 'What They Say About Me';
// Simple state for carousel // Simple state for carousel
let currentIndex = $state(0); let currentIndex = $state(0);
const totalSlides = testimonials.length; const totalSlides = testimonials.length;
function next() { function next() {
currentIndex = (currentIndex + 1) % totalSlides; currentIndex = (currentIndex + 1) % totalSlides;
} }
function prev() { function prev() {
currentIndex = (currentIndex - 1 + totalSlides) % totalSlides; currentIndex = (currentIndex - 1 + totalSlides) % totalSlides;
} }
</script> </script>
<div class="relative min-h-[400px]"> <div class="relative min-h-[400px]">
<div class="flex flex-col items-center px-4 py-12 min-h-[400px]"> <div class="flex flex-col items-center px-4 py-12 min-h-[400px]">
<!-- Title --> <!-- Title -->
<h2 class="text-fg-heading text-2xl md:text-3xl font-light tracking-wide"> <h2 class="text-fg-heading text-2xl md:text-3xl font-light tracking-wide">
{title} {title}
</h2> </h2>
<!-- Testimonial carousel - fills remaining space and centers content vertically --> <!-- Testimonial carousel - fills remaining space and centers content vertically -->
<div class="w-full max-w-3xl flex-1 flex items-center justify-center"> <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. --> <!-- 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"> <div class="grid px-8 text-center w-full pt-4 md:pt-8">
{#each testimonials as testimonial, i} {#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}> <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"> <p class="text-fg-body/85 text-lg md:text-xl font-light leading-relaxed mb-8">
"{testimonial.text}" "{testimonial.text}"
</p> </p>
<p class="text-fg-subheading font-medium tracking-wider"> <p class="text-fg-subheading font-medium tracking-wider">
— {testimonial.title} — {testimonial.title}
</p> </p>
</div> </div>
{/each} {/each}
</div> </div>
</div> </div>
<!-- Navigation arrows --> <!-- Navigation arrows -->
<div class="flex justify-center items-center gap-8"> <div class="flex justify-center items-center gap-8">
<button <button
type="button" type="button"
onclick={prev} 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)]" 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" aria-label="Previous slide"
> >
<svg viewBox="0 0 7.3 13" class="w-2 h-3" fill="none" stroke="currentColor" stroke-width="1.5"> <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"/> <polyline points="6.5,0.5 1.5,6.5 6.5,12.5" stroke-linecap="butt" stroke-linejoin="miter"/>
</svg> </svg>
</button> </button>
<!-- Dots/bullets --> <!-- Dots/bullets -->
<div class="flex gap-3"> <div class="flex gap-3">
{#each testimonials as _, i} {#each testimonials as _, i}
<button <button
type="button" type="button"
class="w-2.5 h-2.5 rounded-full border-2 transition-colors {i === currentIndex ? 'bg-current' : 'border-current'}" 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}" aria-label="Go to slide {i + 1}"
onclick={() => (currentIndex = i)} onclick={() => (currentIndex = i)}
></button> ></button>
{/each} {/each}
</div> </div>
<button <button
type="button" type="button"
onclick={next} 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)]" 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" aria-label="Next slide"
> >
<svg viewBox="0 0 7.3 13" class="w-2 h-3" fill="none" stroke="currentColor" stroke-width="1.5"> <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"/> <polyline points="0.5,0.5 5.5,6.5 0.5,12.5" stroke-linecap="butt" stroke-linejoin="miter"/>
</svg> </svg>
</button> </button>
</div> </div>
</div> </div>
</div> </div>

View file

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

View file

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

View file

@ -1,126 +1,126 @@
<script lang="ts"> <script lang="ts">
import type { CalendarEventRecord, UpcomingCalendarBlockData } from '$lib/types'; import type { CalendarEventRecord, UpcomingCalendarBlockData } from '$lib/types';
import { import {
dateKey, dateKey,
eventMatchesCategories, eventMatchesCategories,
eventOverlapsDay, eventOverlapsDay,
eventRange, eventRange,
formatEventDateRange, formatEventDateRange,
getCurrentAndNextMonths, getCurrentAndNextMonths,
isExternalLink, isExternalLink,
normalizeLink, normalizeLink,
sortEvents sortEvents
} from '$lib/calendar'; } from '$lib/calendar';
let { data = {}, events = [] } = $props<{ let { data = {}, events = [] } = $props<{
data: UpcomingCalendarBlockData; data: UpcomingCalendarBlockData;
events?: CalendarEventRecord[]; events?: CalendarEventRecord[];
}>(); }>();
const weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; const weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
let months = $derived(getCurrentAndNextMonths()); let months = $derived(getCurrentAndNextMonths());
let selectedCategories = $derived(data.categories || []); let selectedCategories = $derived(data.categories || []);
let visibleEvents = $derived(sortEvents(events.filter((event: CalendarEventRecord) => event.published && eventMatchesCategories(event, selectedCategories)))); let visibleEvents = $derived(sortEvents(events.filter((event: CalendarEventRecord) => event.published && eventMatchesCategories(event, selectedCategories))));
function eventsForDay(date: Date) { function eventsForDay(date: Date) {
return visibleEvents.filter((event) => eventOverlapsDay(event, date)); return visibleEvents.filter((event) => eventOverlapsDay(event, date));
} }
function eventStyle(event: CalendarEventRecord) { function eventStyle(event: CalendarEventRecord) {
return `--event-color: ${event.color || '#8a9a7b'};`; return `--event-color: ${event.color || '#8a9a7b'};`;
} }
function segmentMeta(event: CalendarEventRecord, date: Date) { function segmentMeta(event: CalendarEventRecord, date: Date) {
const { start, end } = eventRange(event); const { start, end } = eventRange(event);
const isStart = dateKey(start) === dateKey(date); const isStart = dateKey(start) === dateKey(date);
const isEnd = dateKey(end) === dateKey(date); const isEnd = dateKey(end) === dateKey(date);
const startsWeek = date.getDay() === 0; const startsWeek = date.getDay() === 0;
const endsWeek = date.getDay() === 6; const endsWeek = date.getDay() === 6;
const visualStart = isStart || startsWeek; const visualStart = isStart || startsWeek;
const visualEnd = isEnd || endsWeek; const visualEnd = isEnd || endsWeek;
return { return {
showLabel: visualStart, showLabel: visualStart,
classes: [ classes: [
visualStart ? 'rounded-l-xl' : 'rounded-l-none -ml-3', visualStart ? 'rounded-l-xl' : 'rounded-l-none -ml-3',
visualEnd ? 'rounded-r-xl' : 'rounded-r-none -mr-3', visualEnd ? 'rounded-r-xl' : 'rounded-r-none -mr-3',
visualStart && visualEnd ? 'mx-0' : '', visualStart && visualEnd ? 'mx-0' : '',
!visualStart && !visualEnd ? '-mx-3' : '' !visualStart && !visualEnd ? '-mx-3' : ''
].filter(Boolean).join(' ') ].filter(Boolean).join(' ')
}; };
} }
</script> </script>
<section class="mx-auto max-w-7xl px-6 py-16"> <section class="mx-auto max-w-7xl px-6 py-16">
<div class="mb-10 text-center"> <div class="mb-10 text-center">
<p class="text-sm uppercase tracking-[0.3em] text-sage-dark/75">Calendar</p> <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> <h2 class="font-display mt-2 text-4xl text-charcoal md:text-5xl">{data.title || 'Upcoming Events'}</h2>
</div> </div>
{#if visibleEvents.length === 0} {#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"> <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> <p class="text-charcoal/70">No upcoming events are available for the selected categories.</p>
</div> </div>
{:else} {:else}
<div class="isolate grid gap-8 lg:grid-cols-2"> <div class="isolate grid gap-8 lg:grid-cols-2">
{#each months as month} {#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]"> <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> <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"> <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} {#each weekdays as weekday}<div>{weekday}</div>{/each}
</div> </div>
<div class="grid grid-cols-7 gap-1 overflow-visible"> <div class="grid grid-cols-7 gap-1 overflow-visible">
{#each month.days as day} {#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="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"> <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> <span class="text-sm font-semibold {day.inMonth ? 'text-charcoal/70' : 'text-charcoal/30'}">{day.dayNumber}</span>
</div> </div>
<div class="space-y-1"> <div class="space-y-1">
{#each eventsForDay(day.date) as event} {#each eventsForDay(day.date) as event}
{@const href = normalizeLink(event.link)} {@const href = normalizeLink(event.link)}
{@const label = `${event.name}${event.description ? `: ${event.description}` : ''}`} {@const label = `${event.name}${event.description ? `: ${event.description}` : ''}`}
{@const segment = segmentMeta(event, day.date)} {@const segment = segmentMeta(event, day.date)}
{#if href} {#if href}
<a <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}" 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} href={href}
target={isExternalLink(href) ? '_blank' : undefined} target={isExternalLink(href) ? '_blank' : undefined}
rel={isExternalLink(href) ? 'noreferrer' : undefined} rel={isExternalLink(href) ? 'noreferrer' : undefined}
style={eventStyle(event)} style={eventStyle(event)}
aria-label={label} aria-label={label}
> >
<span class="absolute inset-0 bg-[var(--event-color)] {segment.classes}"></span> <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="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"> <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> <strong class="block">{event.name}</strong>
<span class="block opacity-80">{formatEventDateRange(event)}</span> <span class="block opacity-80">{formatEventDateRange(event)}</span>
{#if event.description}<span class="mt-1 block">{event.description}</span>{/if} {#if event.description}<span class="mt-1 block">{event.description}</span>{/if}
</span> </span>
</a> </a>
{:else} {:else}
<span <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}" 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)} style={eventStyle(event)}
tabindex="0" tabindex="0"
role="button" role="button"
aria-label={label} aria-label={label}
> >
<span class="absolute inset-0 bg-[var(--event-color)] {segment.classes}"></span> <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="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"> <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> <strong class="block">{event.name}</strong>
<span class="block opacity-80">{formatEventDateRange(event)}</span> <span class="block opacity-80">{formatEventDateRange(event)}</span>
{#if event.description}<span class="mt-1 block">{event.description}</span>{/if} {#if event.description}<span class="mt-1 block">{event.description}</span>{/if}
</span> </span>
</span> </span>
{/if} {/if}
{/each} {/each}
</div> </div>
</div> </div>
{/each} {/each}
</div> </div>
</div> </div>
{/each} {/each}
</div> </div>
{/if} {/if}
</section> </section>

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,89 +1,89 @@
import { json } from '@sveltejs/kit'; import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types'; import type { RequestHandler } from './$types';
import { import {
extractImageUrls, extractImageUrls,
fetchImageAsBase64, fetchImageAsBase64,
replaceUrlsWithKeys, replaceUrlsWithKeys,
urlToKey, urlToKey,
type SiteExport type SiteExport
} from '$lib/exportImport'; } from '$lib/exportImport';
import { normalizeEvent } from '$lib/calendar'; import { normalizeEvent } from '$lib/calendar';
export const GET: RequestHandler = async ({ locals }) => { export const GET: RequestHandler = async ({ locals }) => {
// Fetch all pages // Fetch all pages
const pages = await locals.pb.collection('pages').getFullList({ sort: 'slug' }); const pages = await locals.pb.collection('pages').getFullList({ sort: 'slug' });
// Fetch all globals // Fetch all globals
const globals = await locals.pb.collection('globals').getFullList(); const globals = await locals.pb.collection('globals').getFullList();
const events = await locals.pb.collection('events').getFullList({ sort: 'start' }).catch(() => []); const events = await locals.pb.collection('events').getFullList({ sort: 'start' }).catch(() => []);
// Collect all image URLs from pages and globals // Collect all image URLs from pages and globals
const allUrls = new Set<string>(); const allUrls = new Set<string>();
for (const page of pages) { for (const page of pages) {
for (const url of extractImageUrls(page)) allUrls.add(url); for (const url of extractImageUrls(page)) allUrls.add(url);
} }
for (const g of globals) { for (const g of globals) {
for (const url of extractImageUrls(g)) allUrls.add(url); for (const url of extractImageUrls(g)) allUrls.add(url);
} }
// Fetch each image as base64 // Fetch each image as base64
const images: Record<string, string> = {}; const images: Record<string, string> = {};
for (const url of allUrls) { for (const url of allUrls) {
try { try {
const key = urlToKey(url); const key = urlToKey(url);
images[key] = await fetchImageAsBase64(url); images[key] = await fetchImageAsBase64(url);
} catch (e) { } catch (e) {
console.warn(`Could not fetch image: ${url}`, e); console.warn(`Could not fetch image: ${url}`, e);
} }
} }
// Build URL → key mapping // Build URL → key mapping
const urlToKeyMap = new Map<string, string>(); const urlToKeyMap = new Map<string, string>();
for (const url of allUrls) { for (const url of allUrls) {
urlToKeyMap.set(url, urlToKey(url)); urlToKeyMap.set(url, urlToKey(url));
} }
// Replace URLs with placeholders in pages // Replace URLs with placeholders in pages
const exportPages = pages.map((p) => ({ const exportPages = pages.map((p) => ({
slug: p.slug, slug: p.slug,
title: p.title, title: p.title,
blocks: replaceUrlsWithKeys(p.blocks, urlToKeyMap) as typeof p.blocks, blocks: replaceUrlsWithKeys(p.blocks, urlToKeyMap) as typeof p.blocks,
published: p.published published: p.published
})); }));
// Replace URLs with placeholders in globals // Replace URLs with placeholders in globals
const exportGlobals = globals.map((g) => ({ const exportGlobals = globals.map((g) => ({
key: g.key, key: g.key,
data: replaceUrlsWithKeys(g.data, urlToKeyMap) as Record<string, unknown> data: replaceUrlsWithKeys(g.data, urlToKeyMap) as Record<string, unknown>
})); }));
const exportEvents = events.map((record) => { const exportEvents = events.map((record) => {
const event = normalizeEvent(record); const event = normalizeEvent(record);
return { return {
name: event.name, name: event.name,
start: event.start, start: event.start,
end: event.end, end: event.end,
description: event.description, description: event.description,
color: event.color, color: event.color,
link: event.link, link: event.link,
categories: event.categories, categories: event.categories,
published: event.published, published: event.published,
allDay: event.allDay allDay: event.allDay
}; };
}); });
const exportData: SiteExport = { const exportData: SiteExport = {
version: 1, version: 1,
exportedAt: new Date().toISOString(), exportedAt: new Date().toISOString(),
pages: exportPages, pages: exportPages,
globals: exportGlobals, globals: exportGlobals,
events: exportEvents, events: exportEvents,
images images
}; };
return json(exportData, { return json(exportData, {
headers: { headers: {
'Content-Disposition': `attachment; filename="cms-export-${new Date().toISOString().slice(0, 10)}.json"` '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 { env } from '$env/dynamic/public';
import { error, json } from '@sveltejs/kit'; import { error, json } from '@sveltejs/kit';
import type { RequestHandler } from './$types'; import type { RequestHandler } from './$types';
import { import {
dataUriToFile, dataUriToFile,
restorePlaceholders, restorePlaceholders,
type SiteExport type SiteExport
} from '$lib/exportImport'; } from '$lib/exportImport';
export const POST: RequestHandler = async ({ request, locals }) => { export const POST: RequestHandler = async ({ request, locals }) => {
const body = (await request.json()) as SiteExport; const body = (await request.json()) as SiteExport;
if (!body || body.version !== 1) { if (!body || body.version !== 1) {
throw error(400, 'Invalid or unsupported export file.'); throw error(400, 'Invalid or unsupported export file.');
} }
const results = { const results = {
imagesUploaded: 0, imagesUploaded: 0,
pagesImported: 0, pagesImported: 0,
globalsImported: 0, globalsImported: 0,
eventsImported: 0, eventsImported: 0,
errors: [] as string[] errors: [] as string[]
}; };
// 1. Upload images to PocketBase media collection // 1. Upload images to PocketBase media collection
// Build a map: placeholder key → new PocketBase URL // Build a map: placeholder key → new PocketBase URL
const keyToUrl = new Map<string, string>(); const keyToUrl = new Map<string, string>();
for (const [key, dataUri] of Object.entries(body.images)) { for (const [key, dataUri] of Object.entries(body.images)) {
try { try {
// Derive a filename from the key (e.g. "abc12345_logo.png") // Derive a filename from the key (e.g. "abc12345_logo.png")
const filename = key.replace(/[^a-zA-Z0-9._-]/g, '_') || 'image.png'; const filename = key.replace(/[^a-zA-Z0-9._-]/g, '_') || 'image.png';
const file = dataUriToFile(dataUri, filename); const file = dataUriToFile(dataUri, filename);
const formData = new FormData(); const formData = new FormData();
formData.append('file', file); formData.append('file', file);
formData.append('alt', filename.replace(/\.[^/.]+$/, '').replace(/[-_]/g, ' ')); formData.append('alt', filename.replace(/\.[^/.]+$/, '').replace(/[-_]/g, ' '));
const record = await locals.pb.collection('media').create(formData); const record = await locals.pb.collection('media').create(formData);
const publicUrl = env.PUBLIC_POCKETBASE_URL || 'http://localhost:8090'; const publicUrl = env.PUBLIC_POCKETBASE_URL || 'http://localhost:8080';
const newUrl = `${publicUrl}/api/files/${record.collectionId}/${record.id}/${record.file}`; const newUrl = `${publicUrl}/api/files/${record.collectionId}/${record.id}/${record.file}`;
keyToUrl.set(key, newUrl); keyToUrl.set(key, newUrl);
results.imagesUploaded++; results.imagesUploaded++;
} catch (e) { } catch (e) {
results.errors.push(`Failed to upload image "${key}": ${e instanceof Error ? e.message : String(e)}`); results.errors.push(`Failed to upload image "${key}": ${e instanceof Error ? e.message : String(e)}`);
} }
} }
// 2. Import pages // 2. Import pages
for (const page of body.pages) { for (const page of body.pages) {
try { try {
const blocks = restorePlaceholders(page.blocks, keyToUrl); const blocks = restorePlaceholders(page.blocks, keyToUrl);
// Try to find existing page by slug // Try to find existing page by slug
let existing; let existing;
try { try {
existing = await locals.pb.collection('pages').getFirstListItem(`slug = "${page.slug}"`); existing = await locals.pb.collection('pages').getFirstListItem(`slug = "${page.slug}"`);
} catch { } catch {
existing = null; existing = null;
} }
if (existing) { if (existing) {
await locals.pb.collection('pages').update(existing.id, { await locals.pb.collection('pages').update(existing.id, {
title: page.title, title: page.title,
blocks, blocks,
published: page.published published: page.published
}); });
} else { } else {
await locals.pb.collection('pages').create({ await locals.pb.collection('pages').create({
slug: page.slug, slug: page.slug,
title: page.title, title: page.title,
blocks, blocks,
published: page.published published: page.published
}); });
} }
results.pagesImported++; results.pagesImported++;
} catch (e) { } catch (e) {
results.errors.push(`Failed to import page "${page.slug}": ${e instanceof Error ? e.message : String(e)}`); results.errors.push(`Failed to import page "${page.slug}": ${e instanceof Error ? e.message : String(e)}`);
} }
} }
// 3. Import globals // 3. Import globals
for (const g of body.globals) { for (const g of body.globals) {
try { try {
const data = restorePlaceholders(g.data, keyToUrl); const data = restorePlaceholders(g.data, keyToUrl);
let existing; let existing;
try { try {
existing = await locals.pb.collection('globals').getFirstListItem(`key = "${g.key}"`); existing = await locals.pb.collection('globals').getFirstListItem(`key = "${g.key}"`);
} catch { } catch {
existing = null; existing = null;
} }
if (existing) { if (existing) {
await locals.pb.collection('globals').update(existing.id, { data }); await locals.pb.collection('globals').update(existing.id, { data });
} else { } else {
await locals.pb.collection('globals').create({ key: g.key, data }); await locals.pb.collection('globals').create({ key: g.key, data });
} }
results.globalsImported++; results.globalsImported++;
} catch (e) { } catch (e) {
results.errors.push(`Failed to import global "${g.key}": ${e instanceof Error ? e.message : String(e)}`); results.errors.push(`Failed to import global "${g.key}": ${e instanceof Error ? e.message : String(e)}`);
} }
} }
// 4. Import events // 4. Import events
for (const event of body.events || []) { for (const event of body.events || []) {
try { try {
let existing; let existing;
try { try {
existing = await locals.pb.collection('events').getFirstListItem(`name = "${event.name}" && start = "${event.start}"`); existing = await locals.pb.collection('events').getFirstListItem(`name = "${event.name}" && start = "${event.start}"`);
} catch { } catch {
existing = null; existing = null;
} }
const payload = { const payload = {
name: event.name, name: event.name,
start: event.start, start: event.start,
end: event.end || null, end: event.end || null,
description: event.description || '', description: event.description || '',
color: event.color || '#8a9a7b', color: event.color || '#8a9a7b',
link: event.link || '', link: event.link || '',
categories: event.categories || [], categories: event.categories || [],
published: Boolean(event.published), published: Boolean(event.published),
allDay: event.allDay !== false allDay: event.allDay !== false
}; };
if (existing) { if (existing) {
await locals.pb.collection('events').update(existing.id, payload); await locals.pb.collection('events').update(existing.id, payload);
} else { } else {
await locals.pb.collection('events').create(payload); await locals.pb.collection('events').create(payload);
} }
results.eventsImported++; results.eventsImported++;
} catch (e) { } catch (e) {
results.errors.push(`Failed to import event "${event.name}": ${e instanceof Error ? e.message : String(e)}`); results.errors.push(`Failed to import event "${event.name}": ${e instanceof Error ? e.message : String(e)}`);
} }
} }
return json(results); return json(results);
}; };

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,347 +1,347 @@
{ {
"version": 1, "version": 1,
"exportedAt": "2026-05-27T12:07:00.306Z", "exportedAt": "2026-05-27T12:07:00.306Z",
"pages": [ "pages": [
{ {
"slug": "about", "slug": "about",
"title": "About Me", "title": "About Me",
"blocks": [ "blocks": [
{ {
"data": { "data": {
"_background": { "_background": {
"attachment": "fixed", "attachment": "fixed",
"color": "", "color": "",
"imageAlt": "", "imageAlt": "",
"imageUrl": "https://static.tildacdn.one/tild3164-6166-4138-a264-313437663833/chelsea-shapouri-ZN2.jpg", "imageUrl": "https://static.tildacdn.one/tild3164-6166-4138-a264-313437663833/chelsea-shapouri-ZN2.jpg",
"overlay": true, "overlay": true,
"overlayOpacity": 40, "overlayOpacity": 40,
"type": "image" "type": "image"
}, },
"_foreground": { "_foreground": {
"headingColor": "#ffffff", "headingColor": "#ffffff",
"mode": "custom", "mode": "custom",
"subheadingColor": "#eacb8b", "subheadingColor": "#eacb8b",
"textColor": "#eaca85" "textColor": "#eaca85"
}, },
"buttonLabel": "", "buttonLabel": "",
"buttonUrl": "", "buttonUrl": "",
"heading": "About Me", "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." "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", "id": "7f01e183-62ea-4f3c-ab69-a312d8b5df01",
"type": "hero" "type": "hero"
}, },
{ {
"data": { "data": {
"_background": { "_background": {
"attachment": "scroll", "attachment": "scroll",
"color": "", "color": "",
"overlay": false, "overlay": false,
"overlayOpacity": 40, "overlayOpacity": 40,
"type": "none" "type": "none"
}, },
"_foreground": { "_foreground": {
"headingColor": "#903c49", "headingColor": "#903c49",
"mode": "custom" "mode": "custom"
}, },
"alt": "", "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>", "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", "imagePosition": "right",
"url": "https://static.tildacdn.one/tild6363-3837-4530-a330-616562363438/2_DSC3595_web.jpg" "url": "https://static.tildacdn.one/tild6363-3837-4530-a330-616562363438/2_DSC3595_web.jpg"
}, },
"id": "47a5dbed-a891-4d3f-92d9-e5dddcdeb61c", "id": "47a5dbed-a891-4d3f-92d9-e5dddcdeb61c",
"type": "image_text" "type": "image_text"
}, },
{ {
"data": { "data": {
"_background": { "_background": {
"attachment": "scroll", "attachment": "scroll",
"color": "", "color": "",
"overlay": false, "overlay": false,
"overlayOpacity": 40, "overlayOpacity": 40,
"type": "none" "type": "none"
}, },
"_foreground": { "_foreground": {
"headingColor": "#041b65", "headingColor": "#041b65",
"mode": "custom" "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>" "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", "id": "2643c5a0-0530-4ac6-928f-203bda471021",
"type": "text" "type": "text"
}, },
{ {
"data": { "data": {
"_background": { "_background": {
"attachment": "scroll", "attachment": "scroll",
"color": "", "color": "",
"imageAlt": "", "imageAlt": "",
"imageUrl": "https://static.tildacdn.one/tild3862-3762-4666-b036-613061613862/image4.jpg", "imageUrl": "https://static.tildacdn.one/tild3862-3762-4666-b036-613061613862/image4.jpg",
"overlay": true, "overlay": true,
"overlayOpacity": 40, "overlayOpacity": 40,
"type": "image" "type": "image"
}, },
"_foreground": { "_foreground": {
"headingColor": "#ffffff", "headingColor": "#ffffff",
"mode": "custom", "mode": "custom",
"subheadingColor": "#ff0000", "subheadingColor": "#ff0000",
"textColor": "#ffffff" "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>" "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", "id": "b9e5d1a2-511b-43b8-9b59-3c9183b1a56c",
"type": "text" "type": "text"
}, },
{ {
"data": { "data": {
"_background": { "_background": {
"attachment": "scroll", "attachment": "scroll",
"color": "", "color": "",
"overlay": false, "overlay": false,
"overlayOpacity": 40, "overlayOpacity": 40,
"type": "none" "type": "none"
}, },
"_foreground": { "_foreground": {
"headingColor": "#041b65", "headingColor": "#041b65",
"mode": "custom" "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>" "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", "id": "67e65e53-010a-410b-ac0c-2b027a1fbe76",
"type": "text" "type": "text"
}, },
{ {
"data": { "data": {
"_background": { "_background": {
"attachment": "scroll", "attachment": "scroll",
"color": "", "color": "",
"overlay": false, "overlay": false,
"overlayOpacity": 40, "overlayOpacity": 40,
"type": "none" "type": "none"
}, },
"_foreground": { "_foreground": {
"headingColor": "#903c49", "headingColor": "#903c49",
"mode": "custom" "mode": "custom"
}, },
"alt": "", "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>", "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", "imagePosition": "left",
"url": "https://static.tildacdn.one/tild3066-3831-4130-a130-313234333461/_DSC3507_web.jpg" "url": "https://static.tildacdn.one/tild3066-3831-4130-a130-313234333461/_DSC3507_web.jpg"
}, },
"id": "7ac7781f-a989-4850-b16d-4c5154428c22", "id": "7ac7781f-a989-4850-b16d-4c5154428c22",
"type": "image_text" "type": "image_text"
}, },
{ {
"data": { "data": {
"_background": { "_background": {
"attachment": "scroll", "attachment": "scroll",
"color": "", "color": "",
"overlay": false, "overlay": false,
"overlayOpacity": 40, "overlayOpacity": 40,
"type": "none" "type": "none"
}, },
"alignment": "center", "alignment": "center",
"href": "/book", "href": "/book",
"label": "MORE ABOUT SESSIONS", "label": "MORE ABOUT SESSIONS",
"size": "lg", "size": "lg",
"variant": "primary" "variant": "primary"
}, },
"id": "fbc3a78d-77b4-445e-8880-f9bc731fc483", "id": "fbc3a78d-77b4-445e-8880-f9bc731fc483",
"type": "button" "type": "button"
}, },
{ {
"data": { "data": {
"_background": { "_background": {
"attachment": "scroll", "attachment": "scroll",
"color": "", "color": "",
"overlay": false, "overlay": false,
"overlayOpacity": 40, "overlayOpacity": 40,
"type": "none" "type": "none"
}, },
"height": 64 "height": 64
}, },
"id": "67e8c713-80e8-48a2-9a8b-804b14d8405a", "id": "67e8c713-80e8-48a2-9a8b-804b14d8405a",
"type": "spacer" "type": "spacer"
}, },
{ {
"data": { "data": {
"_background": { "_background": {
"attachment": "scroll", "attachment": "scroll",
"color": "#eaca85", "color": "#eaca85",
"overlay": false, "overlay": false,
"overlayOpacity": 40, "overlayOpacity": 40,
"type": "color" "type": "color"
}, },
"_foreground": { "_foreground": {
"headingColor": "#903c49", "headingColor": "#903c49",
"mode": "custom" "mode": "custom"
}, },
"items": [ "items": [
{ {
"description": "2023, Los Angeles, 100 hours", "description": "2023, Los Angeles, 100 hours",
"title": "School Of The Work Of Byron Katie" "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", "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" "title": "Zen Shiatsu School"
}, },
{ {
"description": "2020, Mundekulla, Sweden (with Ernest Holm Svendsen), 50 hours", "description": "2020, Mundekulla, Sweden (with Ernest Holm Svendsen), 50 hours",
"title": "Scandinavian Summer Camp, The Work of Byron Katie" "title": "Scandinavian Summer Camp, The Work of Byron Katie"
}, },
{ {
"description": "2017, Prague, Czech Republic (Peter Walker), 20 hours", "description": "2017, Prague, Czech Republic (Peter Walker), 20 hours",
"title": "Baby Massage Course" "title": "Baby Massage Course"
}, },
{ {
"description": "2016, Nowa Morawa, Poland, 80 hours", "description": "2016, Nowa Morawa, Poland, 80 hours",
"title": " Shaman's course \"Dancing With Gods\"" "title": " Shaman's course \"Dancing With Gods\""
}, },
{ {
"description": "2015 - 2017 Acupressure online course, California Acupressure Institute (Michael Reed Gach), 10 months, 120 hours", "description": "2015 - 2017 Acupressure online course, California Acupressure Institute (Michael Reed Gach), 10 months, 120 hours",
"title": "Acupressure Master Program" "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", "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" "title": "Fasting Courses"
}, },
{ {
"description": "2016, Course for professional Tantric massouse, Republic (Daniela Lukesova), 50 hours", "description": "2016, Course for professional Tantric massouse, Republic (Daniela Lukesova), 50 hours",
"title": "Holistic Sensual Massage" "title": "Holistic Sensual Massage"
}, },
{ {
"description": "2014 - 2016, Poland (Mario and Gaya Wisniewski), 400 hours", "description": "2014 - 2016, Poland (Mario and Gaya Wisniewski), 400 hours",
"title": "2 Year Training in Heart Tantra School" "title": "2 Year Training in Heart Tantra School"
}, },
{ {
"description": "2016, Hammar, Norway, 2 weekends per year, 110 hours", "description": "2016, Hammar, Norway, 2 weekends per year, 110 hours",
"title": "Tai Chi Course" "title": "Tai Chi Course"
}, },
{ {
"description": "2012 - 2016, Oslo, Norway, 100 hours", "description": "2012 - 2016, Oslo, Norway, 100 hours",
"title": "Karate Training" "title": "Karate Training"
}, },
{ {
"description": "2012 - 2016, 3 times a year intense course in self-development (Kenny Johnnson), 650 hours", "description": "2012 - 2016, 3 times a year intense course in self-development (Kenny Johnnson), 650 hours",
"title": "The Three Trainings of 3TH2N" "title": "The Three Trainings of 3TH2N"
}, },
{ {
"description": "2012 - 2016, Norway and Spain (Kenny Johnson) + once a week training, 400 hours", "description": "2012 - 2016, Norway and Spain (Kenny Johnson) + once a week training, 400 hours",
"title": "Chi Kung, Tai Chi, Eternal Youth Yoga System" "title": "Chi Kung, Tai Chi, Eternal Youth Yoga System"
}, },
{ {
"description": "2014, Winna Góra, Poland, 80 hours", "description": "2014, Winna Góra, Poland, 80 hours",
"title": "Shaman's seminar \"The Hero's Journey\"" "title": "Shaman's seminar \"The Hero's Journey\""
}, },
{ {
"description": "2013, levels 1 and 2, Krakow, Poland (Choa Kok Sui) 30 hours", "description": "2013, levels 1 and 2, Krakow, Poland (Choa Kok Sui) 30 hours",
"title": "Prana Healing Course" "title": "Prana Healing Course"
}, },
{ {
"description": "2001 - 2010, Kuan Um school, group retreat in Poland, Hungary, Czech Republic and Norway, approximately 500 hours", "description": "2001 - 2010, Kuan Um school, group retreat in Poland, Hungary, Czech Republic and Norway, approximately 500 hours",
"title": "Zen Meditation Course in KUSZ" "title": "Zen Meditation Course in KUSZ"
}, },
{ {
"description": "1987 - 1992, Business and Economics, Statistics, Econometrics, Administration, Graduate Civil Economist, Wroclaw, Poland", "description": "1987 - 1992, Business and Economics, Statistics, Econometrics, Administration, Graduate Civil Economist, Wroclaw, Poland",
"title": "Business Academy" "title": "Business Academy"
} }
] ]
}, },
"id": "6c3affd2-4ce5-463f-8702-225a8c393354", "id": "6c3affd2-4ce5-463f-8702-225a8c393354",
"type": "timeline" "type": "timeline"
}, },
{ {
"data": { "data": {
"_background": { "_background": {
"attachment": "scroll", "attachment": "scroll",
"color": "#eaca85", "color": "#eaca85",
"overlay": false, "overlay": false,
"overlayOpacity": 40, "overlayOpacity": 40,
"type": "color" "type": "color"
}, },
"alignment": "center", "alignment": "center",
"href": "/book", "href": "/book",
"label": "BOOK A SESSION", "label": "BOOK A SESSION",
"size": "lg", "size": "lg",
"variant": "primary" "variant": "primary"
}, },
"id": "c17182a2-5dfc-43e0-ba2a-6d0718e5df38", "id": "c17182a2-5dfc-43e0-ba2a-6d0718e5df38",
"type": "button" "type": "button"
}, },
{ {
"data": { "data": {
"_background": { "_background": {
"attachment": "scroll", "attachment": "scroll",
"color": "#eaca85", "color": "#eaca85",
"overlay": false, "overlay": false,
"overlayOpacity": 40, "overlayOpacity": 40,
"type": "color" "type": "color"
}, },
"height": 64 "height": 64
}, },
"id": "86b8787d-7fa6-40ab-8d96-24ab9dea9396", "id": "86b8787d-7fa6-40ab-8d96-24ab9dea9396",
"type": "spacer" "type": "spacer"
} }
], ],
"published": true "published": true
} }
], ],
"globals": [ "globals": [
{ {
"key": "header", "key": "header",
"data": { "data": {
"ctaButton": { "ctaButton": {
"href": "/book", "href": "/book",
"label": "Book Now" "label": "Book Now"
}, },
"logo": { "logo": {
"alt": "Massage studio logo", "alt": "Massage studio logo",
"url": "" "url": ""
}, },
"navLinks": [ "navLinks": [
{ {
"href": "/", "href": "/",
"label": "Home" "label": "Home"
}, },
{ {
"href": "/about", "href": "/about",
"label": "About" "label": "About"
}, },
{ {
"href": "/services", "href": "/services",
"label": "Services" "label": "Services"
} }
] ]
} }
}, },
{ {
"key": "colors", "key": "colors",
"data": { "data": {
"accent": "#eacb8b", "accent": "#eacb8b",
"background": "#faf8f5", "background": "#faf8f5",
"heading": "#2c2c2c", "heading": "#2c2c2c",
"primary": "#903c49", "primary": "#903c49",
"subheading": "#4a4a4a", "subheading": "#4a4a4a",
"text": "#2c2c2c" "text": "#2c2c2c"
} }
}, },
{ {
"key": "footer", "key": "footer",
"data": { "data": {
"address": "", "address": "",
"businessName": "Eva Shafik Massage", "businessName": "Eva Shafik Massage",
"copyrightText": "© 2026 Eva Shafik Massage. All rights reserved.", "copyrightText": "© 2026 Eva Shafik Massage. All rights reserved.",
"email": "", "email": "",
"phone": "", "phone": "",
"socialLinks": [ "socialLinks": [
{ {
"platform": "instagram", "platform": "instagram",
"url": "" "url": ""
} }
], ],
"tagline": "Warm, restorative massage therapy for everyday wellbeing." "tagline": "Warm, restorative massage therapy for everyday wellbeing."
} }
} }
], ],
"images": {} "images": {}
} }

View file

@ -1,29 +1,43 @@
services: services:
pocketbase: pocketbase:
image: spectado/pocketbase:latest image: spectado/pocketbase:latest
container_name: massage-pocketbase container_name: massage-pocketbase
restart: unless-stopped restart: unless-stopped
ports: # Internal only — accessed via the caddy reverse proxy
- "8090:80" expose:
volumes: - "80"
- pocketbase:/pb/pb_data volumes:
- pocketbase:/pb/pb_data
app:
build: app:
context: . build:
dockerfile: Dockerfile context: .
container_name: massage-app dockerfile: Dockerfile
restart: unless-stopped container_name: massage-app
depends_on: restart: unless-stopped
- pocketbase depends_on:
environment: - pocketbase
POCKETBASE_INTERNAL_URL: http://pocketbase:80 environment:
PUBLIC_POCKETBASE_URL: http://localhost:8090 POCKETBASE_INTERNAL_URL: http://pocketbase:80
ORIGIN: http://localhost:3000 PUBLIC_POCKETBASE_URL: http://localhost:8080
BODY_SIZE_LIMIT: 5242880 # 5MB ORIGIN: http://localhost:8080
ports: BODY_SIZE_LIMIT: 5242880 # 5MB
- "3000:3000" # Internal only — served via the caddy reverse proxy
expose:
volumes: - "3000"
pocketbase:
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", "id": "pbc_pages000001",
"name": "pages", "name": "pages",
"type": "base", "type": "base",
"system": false, "system": false,
"listRule": "published = true || @request.auth.id != ''", "listRule": "published = true || @request.auth.id != ''",
"viewRule": "published = true || @request.auth.id != ''", "viewRule": "published = true || @request.auth.id != ''",
"createRule": "@request.auth.id != ''", "createRule": "@request.auth.id != ''",
"updateRule": "@request.auth.id != ''", "updateRule": "@request.auth.id != ''",
"deleteRule": "@request.auth.id != ''", "deleteRule": "@request.auth.id != ''",
"fields": [ "fields": [
{ {
"id": "text_slug00001", "id": "text_slug00001",
"name": "slug", "name": "slug",
"type": "text", "type": "text",
"system": false, "system": false,
"required": true, "required": true,
"presentable": true, "presentable": true,
"unique": true, "unique": true,
"options": { "options": {
"min": null, "min": null,
"max": 120, "max": 120,
"pattern": "" "pattern": ""
} }
}, },
{ {
"id": "text_title0001", "id": "text_title0001",
"name": "title", "name": "title",
"type": "text", "type": "text",
"system": false, "system": false,
"required": true, "required": true,
"presentable": false, "presentable": false,
"unique": false, "unique": false,
"options": { "options": {
"min": null, "min": null,
"max": 180, "max": 180,
"pattern": "" "pattern": ""
} }
}, },
{ {
"id": "json_blocks001", "id": "json_blocks001",
"name": "blocks", "name": "blocks",
"type": "json", "type": "json",
"system": false, "system": false,
"required": false, "required": false,
"presentable": false, "presentable": false,
"unique": false, "unique": false,
"options": { "options": {
"maxSize": 2000000 "maxSize": 2000000
} }
}, },
{ {
"id": "bool_published", "id": "bool_published",
"name": "published", "name": "published",
"type": "bool", "type": "bool",
"system": false, "system": false,
"required": false, "required": false,
"presentable": false, "presentable": false,
"unique": false, "unique": false,
"options": {} "options": {}
} }
], ],
"indexes": [], "indexes": [],
"options": {} "options": {}
}, },
{ {
"id": "pbc_globals0001", "id": "pbc_globals0001",
"name": "globals", "name": "globals",
"type": "base", "type": "base",
"system": false, "system": false,
"listRule": "", "listRule": "",
"viewRule": "", "viewRule": "",
"createRule": "@request.auth.id != ''", "createRule": "@request.auth.id != ''",
"updateRule": "@request.auth.id != ''", "updateRule": "@request.auth.id != ''",
"deleteRule": "@request.auth.id != ''", "deleteRule": "@request.auth.id != ''",
"fields": [ "fields": [
{ {
"id": "text_key000001", "id": "text_key000001",
"name": "key", "name": "key",
"type": "text", "type": "text",
"system": false, "system": false,
"required": true, "required": true,
"presentable": true, "presentable": true,
"unique": true, "unique": true,
"options": { "options": {
"min": null, "min": null,
"max": 80, "max": 80,
"pattern": "" "pattern": ""
} }
}, },
{ {
"id": "json_data00001", "id": "json_data00001",
"name": "data", "name": "data",
"type": "json", "type": "json",
"system": false, "system": false,
"required": false, "required": false,
"presentable": false, "presentable": false,
"unique": false, "unique": false,
"options": { "options": {
"maxSize": 1000000 "maxSize": 1000000
} }
} }
], ],
"indexes": [], "indexes": [],
"options": {} "options": {}
}, },
{ {
"id": "pbc_media00001", "id": "pbc_media00001",
"name": "media", "name": "media",
"type": "base", "type": "base",
"system": false, "system": false,
"listRule": "", "listRule": "",
"viewRule": "", "viewRule": "",
"createRule": "@request.auth.id != ''", "createRule": "@request.auth.id != ''",
"updateRule": "@request.auth.id != ''", "updateRule": "@request.auth.id != ''",
"deleteRule": "@request.auth.id != ''", "deleteRule": "@request.auth.id != ''",
"fields": [ "fields": [
{ {
"id": "file_file00001", "id": "file_file00001",
"name": "file", "name": "file",
"type": "file", "type": "file",
"system": false, "system": false,
"required": true, "required": true,
"presentable": false, "presentable": false,
"unique": false, "unique": false,
"options": { "options": {
"mimeTypes": [ "mimeTypes": [
"image/jpeg", "image/jpeg",
"image/png", "image/png",
"image/webp", "image/webp",
"image/gif", "image/gif",
"image/svg+xml" "image/svg+xml"
], ],
"thumbs": [ "thumbs": [
"300x300", "300x300",
"1200x0" "1200x0"
], ],
"maxSelect": 1, "maxSelect": 1,
"maxSize": 10485760, "maxSize": 10485760,
"protected": false "protected": false
} }
}, },
{ {
"id": "text_alt000001", "id": "text_alt000001",
"name": "alt", "name": "alt",
"type": "text", "type": "text",
"system": false, "system": false,
"required": false, "required": false,
"presentable": false, "presentable": false,
"unique": false, "unique": false,
"options": { "options": {
"min": null, "min": null,
"max": 180, "max": 180,
"pattern": "" "pattern": ""
} }
} }
], ],
"indexes": [], "indexes": [],
"options": {} "options": {}
}, },
{ {
"id": "pbc_events0001", "id": "pbc_events0001",
"name": "events", "name": "events",
"type": "base", "type": "base",
"system": false, "system": false,
"listRule": "published = true || @request.auth.id != ''", "listRule": "published = true || @request.auth.id != ''",
"viewRule": "published = true || @request.auth.id != ''", "viewRule": "published = true || @request.auth.id != ''",
"createRule": "@request.auth.id != ''", "createRule": "@request.auth.id != ''",
"updateRule": "@request.auth.id != ''", "updateRule": "@request.auth.id != ''",
"deleteRule": "@request.auth.id != ''", "deleteRule": "@request.auth.id != ''",
"fields": [ "fields": [
{ {
"id": "text_eventname", "id": "text_eventname",
"name": "name", "name": "name",
"type": "text", "type": "text",
"system": false, "system": false,
"required": true, "required": true,
"presentable": true, "presentable": true,
"unique": false, "unique": false,
"options": { "options": {
"min": null, "min": null,
"max": 180, "max": 180,
"pattern": "" "pattern": ""
} }
}, },
{ {
"id": "date_eventstart", "id": "date_eventstart",
"name": "start", "name": "start",
"type": "date", "type": "date",
"system": false, "system": false,
"required": true, "required": true,
"presentable": false, "presentable": false,
"unique": false, "unique": false,
"options": { "options": {
"min": "", "min": "",
"max": "" "max": ""
} }
}, },
{ {
"id": "date_eventend", "id": "date_eventend",
"name": "end", "name": "end",
"type": "date", "type": "date",
"system": false, "system": false,
"required": false, "required": false,
"presentable": false, "presentable": false,
"unique": false, "unique": false,
"options": { "options": {
"min": "", "min": "",
"max": "" "max": ""
} }
}, },
{ {
"id": "text_eventdesc", "id": "text_eventdesc",
"name": "description", "name": "description",
"type": "text", "type": "text",
"system": false, "system": false,
"required": false, "required": false,
"presentable": false, "presentable": false,
"unique": false, "unique": false,
"options": { "options": {
"min": null, "min": null,
"max": 2000, "max": 2000,
"pattern": "" "pattern": ""
} }
}, },
{ {
"id": "text_eventcolor", "id": "text_eventcolor",
"name": "color", "name": "color",
"type": "text", "type": "text",
"system": false, "system": false,
"required": false, "required": false,
"presentable": false, "presentable": false,
"unique": false, "unique": false,
"options": { "options": {
"min": null, "min": null,
"max": 32, "max": 32,
"pattern": "" "pattern": ""
} }
}, },
{ {
"id": "url_eventlink", "id": "url_eventlink",
"name": "link", "name": "link",
"type": "text", "type": "text",
"system": false, "system": false,
"required": false, "required": false,
"presentable": false, "presentable": false,
"unique": false, "unique": false,
"options": { "options": {
"min": null, "min": null,
"max": 500, "max": 500,
"pattern": "" "pattern": ""
} }
}, },
{ {
"id": "json_eventcats", "id": "json_eventcats",
"name": "categories", "name": "categories",
"type": "json", "type": "json",
"system": false, "system": false,
"required": false, "required": false,
"presentable": false, "presentable": false,
"unique": false, "unique": false,
"options": { "options": {
"maxSize": 200000 "maxSize": 200000
} }
}, },
{ {
"id": "bool_eventpub", "id": "bool_eventpub",
"name": "published", "name": "published",
"type": "bool", "type": "bool",
"system": false, "system": false,
"required": false, "required": false,
"presentable": false, "presentable": false,
"unique": false, "unique": false,
"options": {} "options": {}
}, },
{ {
"id": "bool_eventallday", "id": "bool_eventallday",
"name": "allDay", "name": "allDay",
"type": "bool", "type": "bool",
"system": false, "system": false,
"required": false, "required": false,
"presentable": false, "presentable": false,
"unique": false, "unique": false,
"options": {} "options": {}
} }
], ],
"indexes": [ "indexes": [
"CREATE INDEX `idx_events_start` ON `events` (`start`)", "CREATE INDEX `idx_events_start` ON `events` (`start`)",
"CREATE INDEX `idx_events_published` ON `events` (`published`)" "CREATE INDEX `idx_events_published` ON `events` (`published`)"
], ],
"options": {} "options": {}
} }
] ]