moved page rendering to a different service and access is now behind
admin.DOMAIN www.DOMAIN db.DOMAIN
This commit is contained in:
parent
c7f6b30b87
commit
1027da989e
126 changed files with 6356 additions and 1516 deletions
|
|
@ -1,6 +1,10 @@
|
|||
node_modules
|
||||
app/node_modules
|
||||
app/.svelte-kit
|
||||
app/build
|
||||
app-admin/node_modules
|
||||
app-admin/.svelte-kit
|
||||
app-admin/build
|
||||
app-public/node_modules
|
||||
app-public/.svelte-kit
|
||||
app-public/build
|
||||
packages/shared/node_modules
|
||||
.git
|
||||
pocketbase/pb_data
|
||||
|
|
|
|||
120
AGENTS.md
120
AGENTS.md
|
|
@ -5,36 +5,78 @@
|
|||
- **SvelteKit 2** (SSR, Svelte 5 runes mode) — all `.svelte` files use `$state`, `$derived`, `$props()` etc.
|
||||
- **PocketBase** — REST API via the `pocketbase` SDK (v0.26). Auth, DB, and image storage.
|
||||
- **Tailwind CSS v4** + **DaisyUI 5** — utility-first CSS with DaisyUI components for admin; custom theme for the public site.
|
||||
- **Docker Compose** — three services: `app` (SvelteKit), `pocketbase`, and `caddy` (reverse proxy).
|
||||
- **Docker Compose** — four services: `app-admin`, `app-public`, `pocketbase`, and `caddy` (reverse proxy).
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
app/ # SvelteKit application
|
||||
packages/shared/src/ # Shared code (types, calendar utils)
|
||||
app-admin/ # SvelteKit admin app (serves admin.<domain>)
|
||||
├── src/
|
||||
│ ├── lib/
|
||||
│ │ ├── admin/ # Admin UI components (BlockList, editors)
|
||||
│ │ ├── blocks/ # Public block renderers (one per BlockType)
|
||||
│ │ ├── components/ # Header.svelte, Footer.svelte
|
||||
│ │ ├── blocks/ # Block renderers (duplicated from public — needed for preview iframe)
|
||||
│ │ ├── pb.ts # PocketBase client factory + helpers
|
||||
│ │ └── types.ts # ContentBlock, PageRecord, HeaderGlobal, FooterGlobal
|
||||
│ │ ├── types.ts # Re-exports from $shared
|
||||
│ │ ├── calendar.ts # Re-exports from $shared
|
||||
│ │ └── server/ # Server-only modules (pb-admin)
|
||||
│ ├── routes/
|
||||
│ │ ├── +layout.svelte # Root layout (admin vs public shell)
|
||||
│ │ ├── +page.svelte # Home page (slug=home)
|
||||
│ │ ├── [slug]/ # Dynamic CMS pages
|
||||
│ │ ├── admin/ # Admin area (login, pages, globals)
|
||||
│ │ └── preview/ # Draft preview via sessionStorage
|
||||
│ │ ├── +layout.svelte # Root layout (admin shell: navbar, export/import, logout)
|
||||
│ │ ├── login/ # Admin login
|
||||
│ │ ├── pages/ # Page CRUD + block editor
|
||||
│ │ ├── calendar/ # Event CRUD
|
||||
│ │ ├── items/ # Service/product CRUD
|
||||
│ │ ├── slots/ # Bookable time slot CRUD
|
||||
│ │ ├── orders/ # Read-only order list
|
||||
│ │ ├── globals/ # Header/footer/colors editor
|
||||
│ │ ├── preview/ # Draft preview via sessionStorage (same-origin)
|
||||
│ │ └── api/ # upload, export, import endpoints
|
||||
│ ├── hooks.server.ts # Auth guard — all routes except /login
|
||||
│ └── app.css # Tailwind + DaisyUI + custom theme
|
||||
├── static/ # Static assets
|
||||
├── build/ # Production build output
|
||||
├── svelte.config.js # Adapter-node, runes mode forced
|
||||
├── svelte.config.js # Adapter-node, runes mode forced, $shared alias
|
||||
├── vite.config.ts # Tailwind v4 + SvelteKit plugins
|
||||
└── package.json
|
||||
pocketbase/pb_data/ # PocketBase data (mounted volume-mounted)
|
||||
docker-compose.yml # app + pocketbase services
|
||||
Dockerfile # Multi-stage Node 22 build
|
||||
app-public/ # SvelteKit public app (serves *.<domain>)
|
||||
├── src/
|
||||
│ ├── lib/
|
||||
│ │ ├── blocks/ # Block renderers (one per BlockType)
|
||||
│ │ ├── components/ # Header.svelte, Footer.svelte
|
||||
│ │ ├── pb.ts # PocketBase client factory + helpers
|
||||
│ │ ├── types.ts # Re-exports from $shared
|
||||
│ │ ├── calendar.ts # Re-exports from $shared
|
||||
│ │ ├── basket.svelte.ts # Basket store (client-side state)
|
||||
│ │ ├── stripe-client.ts # Stripe.js loader
|
||||
│ │ └── server/ # Server-only modules (pb-admin, basket, stripe)
|
||||
│ ├── routes/
|
||||
│ │ ├── +layout.svelte # Root layout (always renders Header/Footer)
|
||||
│ │ ├── +page.svelte # Home page (slug=home)
|
||||
│ │ ├── [slug]/ # Dynamic CMS pages
|
||||
│ │ ├── api/ # basket, checkout, webhooks endpoints
|
||||
│ │ └── checkout/return/ # Stripe return URL
|
||||
│ ├── hooks.server.ts # Creates PB client in locals (no auth guard)
|
||||
│ └── app.css # Tailwind + DaisyUI + custom theme
|
||||
├── static/ # Static assets
|
||||
├── build/ # Production build output
|
||||
├── svelte.config.js # Adapter-node, runes mode forced, $shared alias
|
||||
├── vite.config.ts # Tailwind v4 + SvelteKit plugins
|
||||
└── package.json
|
||||
pocketbase/pb_data/ # PocketBase data (volume-mounted)
|
||||
docker-compose.yml # app-admin + app-public + pocketbase + caddy services
|
||||
Caddyfile # Subdomain-based routing
|
||||
```
|
||||
|
||||
## Subdomain Routing
|
||||
|
||||
Caddy routes by `Host` header — no path stripping:
|
||||
|
||||
- `admin.{$DOMAIN}:8080` → `app-admin:3001` (admin app)
|
||||
- `db.{$DOMAIN}:8080` → `pocketbase:80` (redirects `/` to `/_/`)
|
||||
- `www.{$DOMAIN}:8080`, `*.{$DOMAIN}:8080` → `app-public:3000` (public app)
|
||||
|
||||
For local dev, `DOMAIN` defaults to `localhost`, so Caddy serves `admin.localhost:8080`, `db.localhost:8080`, `www.localhost:8080`. Caddy's `.localhost` handling works without DNS or hosts-file changes.
|
||||
|
||||
## Key Conventions
|
||||
|
||||
### Svelte 5 Runes Mode
|
||||
|
|
@ -47,15 +89,22 @@ All components use Svelte 5 runes syntax — **never** `export let`, `$:`, or `o
|
|||
- `onclick={handler}` (not `on:click`)
|
||||
|
||||
### Block System
|
||||
Pages are composed of `ContentBlock[]`. Each block has `{ id, type, data }`. Block types are defined in `$lib/types.ts`:
|
||||
`text | image | image_text | timeline | testimonials | services | cta | spacer | horizontal_cards`
|
||||
Pages are composed of `ContentBlock[]`. Each block has `{ id, type, data }`. Block types are defined in `packages/shared/src/types.ts` (re-exported via `$lib/types` in each app):
|
||||
`text | image_text | timeline | hero | button | spacer | testimonials | upcoming_calendar | shop | checkout`
|
||||
|
||||
- **Public renderers**: `$lib/blocks/<Type>Block.svelte` — one per type, receives `data` prop. Currently active: `TextBlock`, `ImageTextBlock`, `TimelineBlock`, `HeroBlock`.
|
||||
- **Admin editors**: `$lib/admin/editors/BlockEditor.svelte` — switches editor UI by type
|
||||
- **Defaults**: `$lib/admin/blockDefaults.ts` — `createBlock(type)` generates a new block with sensible defaults
|
||||
- **Block list**: `$lib/admin/BlockList.svelte` — draggable reorder, select, delete
|
||||
- **Public renderers**: `app-public/src/lib/blocks/<Type>Block.svelte` — one per type, receives `data` prop.
|
||||
- **Admin renderers (for preview)**: `app-admin/src/lib/blocks/<Type>Block.svelte` — duplicated from public so the preview iframe works.
|
||||
- **Admin editors**: `app-admin/src/lib/admin/editors/BlockEditor.svelte` — switches editor UI by type
|
||||
- **Defaults**: `app-admin/src/lib/admin/blockDefaults.ts` — `createBlock(type)` generates a new block with sensible defaults
|
||||
- **Block list**: `app-admin/src/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 `packages/shared/src/types.ts`, create renderer in both `app-public/src/lib/blocks/` and `app-admin/src/lib/blocks/`, add editor case in `app-admin/src/lib/admin/editors/BlockEditor.svelte`, add default in `app-admin/src/lib/admin/blockDefaults.ts`, add import in both `BlockRenderer.svelte` files.
|
||||
|
||||
### Shared Code
|
||||
- `packages/shared/src/types.ts` — all type definitions
|
||||
- `packages/shared/src/calendar.ts` — calendar utilities (used by admin calendar editor and public upcoming calendar block)
|
||||
- Each app's `svelte.config.js` declares `kit.alias.$shared → '../packages/shared/src'`
|
||||
- Each app's `src/lib/types.ts` and `src/lib/calendar.ts` re-export from `$shared` so existing `$lib/types` and `$lib/calendar` imports work
|
||||
|
||||
### PocketBase Integration
|
||||
- Client created in `hooks.server.ts` (`event.locals.pb`) — injected per-request with auth cookie
|
||||
|
|
@ -69,30 +118,35 @@ To add a new block type: add to `BlockType` union in `types.ts`, create renderer
|
|||
- **Prose**: `.prose-wellness` class for rich text content styling
|
||||
|
||||
### Routing
|
||||
- `+layout.server.ts` fetches header/footer globals for every public page
|
||||
- **Admin app** (`app-admin`): All routes except `/login` are auth-guarded in `hooks.server.ts`. The root layout renders the admin shell (navbar, export/import, logout). The `/preview` route reads `sessionStorage` set by the page editor (same-origin, so it works).
|
||||
- **Public app** (`app-public`): No auth guard. The root layout always renders Header/Footer. `+layout.server.ts` fetches header/footer/colors globals + basket/items/slots for every page.
|
||||
- `+page.server.ts` for home fetches `slug = "home" && published = true`
|
||||
- `[slug]/+page.server.ts` fetches by dynamic slug
|
||||
- Admin routes protected in `hooks.server.ts` — redirects to `/admin/login` if unauthenticated
|
||||
|
||||
## Build & Dev Commands
|
||||
|
||||
```sh
|
||||
# Full stack (single entry point on port 8080) — the only supported way to run/develop
|
||||
# Source changes require rebuilding; the container runs `node build`, not a dev server.
|
||||
docker compose up --build
|
||||
# App + PocketBase via Caddy: http://localhost:8080
|
||||
# PocketBase admin: http://localhost:8080/_/
|
||||
DOMAIN=localhost docker compose up --build
|
||||
# Admin app: http://admin.localhost:8080
|
||||
# Public app: http://www.localhost:8080
|
||||
# PocketBase: http://db.localhost:8080/_/
|
||||
|
||||
# Type checking (can run on the host with node_modules present, or inside the container)
|
||||
cd app && npm run check
|
||||
# Type checking (can run on the host with node_modules present)
|
||||
cd app-admin && npm run check
|
||||
cd app-public && npm run check
|
||||
|
||||
# Production build only (run by the Dockerfile)
|
||||
cd app && npm run build
|
||||
# Production build only (run by each app's Dockerfile)
|
||||
cd app-admin && npm run build
|
||||
cd app-public && npm run build
|
||||
```
|
||||
|
||||
## Environment
|
||||
|
||||
- `PUBLIC_POCKETBASE_URL` — public-facing PocketBase URL, accessed through the Caddy reverse proxy (`http://localhost:8080`). Set directly in `docker-compose.yml`.
|
||||
- `POCKETBASE_INTERNAL_URL` — internal Docker network URL (`http://pocketbase:80`). Set directly in `docker-compose.yml`.
|
||||
- `ORIGIN` — SvelteKit origin for SSR (`http://localhost:8080`). Set directly in `docker-compose.yml`.
|
||||
- `DOMAIN` — base domain for subdomain routing. Defaults to `localhost` for local dev. Set in `docker-compose.yml` or `.env`.
|
||||
- `PUBLIC_POCKETBASE_URL` — public-facing PocketBase URL (`http://db.${DOMAIN}:8080`). Set in `docker-compose.yml`.
|
||||
- `POCKETBASE_INTERNAL_URL` — internal Docker network URL (`http://pocketbase:80`). Set in `docker-compose.yml`.
|
||||
- `ORIGIN` — SvelteKit origin for SSR. Differs per app: `http://admin.${DOMAIN}:8080` (admin), `http://www.${DOMAIN}:8080` (public).
|
||||
- `PUBLIC_SITE_URL` — public site URL used by the admin app for cross-subdomain preview links (`http://www.${DOMAIN}:8080`).
|
||||
- Stripe + PocketBase admin secrets are read from a root-level `.env` next to `docker-compose.yml`; see `.env.example`.
|
||||
|
|
|
|||
54
Caddyfile
54
Caddyfile
|
|
@ -1,35 +1,23 @@
|
|||
# Reverse proxy — single port for both the SvelteKit app and PocketBase
|
||||
# Route: /api/basket, /api/checkout/*, /api/webhooks/* → SvelteKit app (commerce endpoints)
|
||||
# /api/* and /_/* → PocketBase
|
||||
# everything else → SvelteKit app
|
||||
# Reverse proxy — subdomain-based routing (plain HTTP on port 8080)
|
||||
# admin.{$DOMAIN} → app-admin (SvelteKit admin app)
|
||||
# db.{$DOMAIN} → PocketBase (redirects / to /_/)
|
||||
# *.{$DOMAIN} → app-public (SvelteKit public app)
|
||||
#
|
||||
# The `http://` prefix disables Caddy's automatic HTTPS so the site is served
|
||||
# as plain HTTP on port 8080. This matches the ORIGIN env vars in
|
||||
# docker-compose.yml (http://admin.${DOMAIN}:8080 etc.) so SvelteKit's CSRF
|
||||
# protection accepts form POSTs.
|
||||
|
||||
:8080 {
|
||||
# SvelteKit commerce endpoints must reach the app, not PocketBase.
|
||||
# These matchers are more specific than the generic /api/* handle below.
|
||||
handle /api/basket {
|
||||
reverse_proxy app:3000
|
||||
}
|
||||
|
||||
handle /api/checkout/* {
|
||||
reverse_proxy app:3000
|
||||
}
|
||||
|
||||
handle /api/webhooks/* {
|
||||
reverse_proxy app:3000
|
||||
}
|
||||
|
||||
# PocketBase REST API (collections, records, files, health)
|
||||
handle /api/* {
|
||||
reverse_proxy pocketbase:80
|
||||
}
|
||||
|
||||
# PocketBase admin UI
|
||||
handle /_/* {
|
||||
reverse_proxy pocketbase:80
|
||||
}
|
||||
|
||||
# Public site + SSR pages
|
||||
handle {
|
||||
reverse_proxy app:3000
|
||||
}
|
||||
http://admin.{$DOMAIN}:8080 {
|
||||
reverse_proxy app-admin:3001
|
||||
}
|
||||
|
||||
http://db.{$DOMAIN}:8080 {
|
||||
# PocketBase admin UI lives at /_/ — redirect bare root there.
|
||||
redir / /_/{path}
|
||||
reverse_proxy pocketbase:80
|
||||
}
|
||||
|
||||
http://www.{$DOMAIN}:8080, http://*.{$DOMAIN}:8080 {
|
||||
reverse_proxy app-public:3000
|
||||
}
|
||||
|
|
|
|||
73
README.md
73
README.md
|
|
@ -4,10 +4,20 @@ A full-stack SvelteKit CMS for a single-operator massage studio. PocketBase prov
|
|||
|
||||
## Stack
|
||||
|
||||
- SvelteKit + SSR
|
||||
- SvelteKit + SSR (two apps: admin and public)
|
||||
- PocketBase REST API via the `pocketbase` SDK
|
||||
- Tailwind CSS v4 + DaisyUI
|
||||
- Docker Compose with three services: `app`, `pocketbase`, and `caddy` (reverse proxy)
|
||||
- Docker Compose with four services: `app-admin`, `app-public`, `pocketbase`, and `caddy` (reverse proxy)
|
||||
|
||||
## Architecture
|
||||
|
||||
The project is split into two independent SvelteKit apps, each serving its own subdomain:
|
||||
|
||||
- **`app-admin`** — serves `admin.<domain>` (admin UI, page editor, CRUD)
|
||||
- **`app-public`** — serves `*.<domain>` (public CMS pages, shop, checkout)
|
||||
- **PocketBase** — serves `db.<domain>` (auth, DB, image storage)
|
||||
|
||||
Shared types and calendar utilities live in `packages/shared/` and are imported via the `$shared` alias declared in each app's `svelte.config.js`.
|
||||
|
||||
## Development
|
||||
|
||||
|
|
@ -19,42 +29,45 @@ The project runs exclusively through Docker Compose. There is no bare host dev m
|
|||
```
|
||||
2. Build and start the full stack:
|
||||
```sh
|
||||
docker compose up --build
|
||||
DOMAIN=localhost docker compose up --build
|
||||
```
|
||||
3. Visit `http://localhost:8080`.
|
||||
3. Visit:
|
||||
- Admin app: `http://admin.localhost:8080`
|
||||
- Public app: `http://www.localhost:8080`
|
||||
- PocketBase admin: `http://db.localhost:8080/_/`
|
||||
|
||||
The single Caddy entry point on port `8080` fronts both the SvelteKit app and PocketBase. Source changes require rebuilding (`docker compose up --build`); the container runs the production build (`node build`), not a dev server.
|
||||
Caddy's `.localhost` handling works without DNS or hosts-file changes. Source changes require rebuilding (`docker compose up --build`); the containers run the production build (`node build`), not a dev server.
|
||||
|
||||
## Docker Compose
|
||||
|
||||
Run the full stack:
|
||||
|
||||
```sh
|
||||
docker compose up --build
|
||||
DOMAIN=localhost docker compose up --build
|
||||
```
|
||||
|
||||
If dependency installation is slow on the first build, enable BuildKit explicitly:
|
||||
|
||||
```sh
|
||||
DOCKER_BUILDKIT=1 docker compose build --progress=plain app
|
||||
DOCKER_BUILDKIT=1 docker compose build --progress=plain app-admin app-public
|
||||
docker compose up
|
||||
```
|
||||
|
||||
Subsequent builds reuse the npm cache declared in the `Dockerfile`.
|
||||
Subsequent builds reuse the npm cache declared in each app's `Dockerfile`.
|
||||
|
||||
- Single entry point (Caddy reverse proxy): **`http://localhost:8080`**
|
||||
- SvelteKit app: `http://localhost:8080/` (or any non-API path)
|
||||
- PocketBase admin UI: `http://localhost:8080/_/`
|
||||
- PocketBase REST API: `http://localhost:8080/api/`
|
||||
- **Admin app**: `http://admin.localhost:8080` → `app-admin:3001`
|
||||
- **Public app**: `http://www.localhost:8080` → `app-public:3000`
|
||||
- **PocketBase admin UI**: `http://db.localhost:8080/_/` (redirects `/` to `/_/`)
|
||||
- **PocketBase REST API**: `http://db.localhost:8080/api/`
|
||||
|
||||
The app container uses two PocketBase URLs:
|
||||
The app containers use two PocketBase URLs:
|
||||
|
||||
- `POCKETBASE_INTERNAL_URL=http://pocketbase:80` for server-side SvelteKit calls from the app container when using the included `spectado/pocketbase` image.
|
||||
- `PUBLIC_POCKETBASE_URL=http://localhost:8080` for browser-side admin uploads and public file URLs. Since the Caddy reverse proxy routes `/api/*` to PocketBase, the public URL points to the proxy.
|
||||
- `POCKETBASE_INTERNAL_URL=http://pocketbase:80` for server-side SvelteKit calls from the app containers when using the included `spectado/pocketbase` image.
|
||||
- `PUBLIC_POCKETBASE_URL=http://db.${DOMAIN}:8080` for browser-side admin uploads and public file URLs. Points to the Caddy reverse proxy so browsers reach PocketBase via the `db` subdomain.
|
||||
|
||||
## PocketBase setup
|
||||
|
||||
1. Open `http://localhost:8080/_/`.
|
||||
1. Open `http://db.localhost:8080/_/`.
|
||||
2. Create the first PocketBase admin user when prompted.
|
||||
3. Import `pb_schema.json` from the PocketBase admin UI collection settings/import flow. This file uses the newer PocketBase `fields` schema format; if PocketBase still reports `Invalid collections configuration`, create the three collections manually using the fields below.
|
||||
4. Create starter records:
|
||||
|
|
@ -93,23 +106,23 @@ Commerce collections (see the Stripe section above for context):
|
|||
|
||||
## Authentication
|
||||
|
||||
Admin routes live under `/admin`. Login accepts either:
|
||||
Admin routes live in the `app-admin` app. Login accepts either:
|
||||
|
||||
- a PocketBase admin account, or
|
||||
- a record from a `users` auth collection if you create one.
|
||||
|
||||
All `/admin` routes except `/admin/login` are guarded in `src/hooks.server.ts`.
|
||||
All routes in `app-admin` except `/login` are guarded in `src/hooks.server.ts`.
|
||||
|
||||
## CMS routes
|
||||
## CMS routes (admin app)
|
||||
|
||||
- `/admin/login` — sign in
|
||||
- `/admin/pages` — list/create pages
|
||||
- `/admin/pages/[slug]` — block editor with draft preview
|
||||
- `/admin/calendar` — events shown by Upcoming Calendar blocks
|
||||
- `/admin/items` — services and products shown in Shop blocks
|
||||
- `/admin/slots` — manually created bookable time slots for services
|
||||
- `/admin/orders` — read-only list of confirmed bookings and purchases
|
||||
- `/admin/globals` — header/footer editor
|
||||
- `/login` — sign in
|
||||
- `/pages` — list/create pages
|
||||
- `/pages/[slug]` — block editor with draft preview
|
||||
- `/calendar` — events shown by Upcoming Calendar blocks
|
||||
- `/items` — services and products shown in Shop blocks
|
||||
- `/slots` — manually created bookable time slots for services
|
||||
- `/orders` — read-only list of confirmed bookings and purchases
|
||||
- `/globals` — header/footer/colors editor
|
||||
|
||||
## Reservations & payments (Stripe)
|
||||
|
||||
|
|
@ -121,13 +134,13 @@ Setup:
|
|||
2. `POCKETBASE_ADMIN_EMAIL` / `POCKETBASE_ADMIN_PASSWORD` are the credentials of the PocketBase superuser you created — the basket/checkout/webhook APIs use a server-side admin client so collection rules can stay admin-only.
|
||||
3. For local webhook testing, forward Stripe events with the CLI:
|
||||
```sh
|
||||
stripe listen --forward-to localhost:8080/api/webhooks/stripe
|
||||
stripe listen --forward-to www.localhost:8080/api/webhooks/stripe
|
||||
```
|
||||
Copy the printed `whsec_…` signing secret into `STRIPE_WEBHOOK_SECRET`.
|
||||
4. Import the updated `pb_schema.json` (adds `items`, `slots`, `baskets`, `basket_lines`, `orders`, `order_lines`). The `basket_lines.slot` partial unique index guarantees two visitors can't hold the same slot.
|
||||
5. Create a published page (e.g. slug `book`) with a `shop` block and a `checkout` block, and point the header CTA at it.
|
||||
|
||||
## Public routes
|
||||
## Public routes (public app)
|
||||
|
||||
- `/` renders `pages.slug = "home"`
|
||||
- `/[slug]` renders any other published page
|
||||
|
|
@ -136,5 +149,5 @@ Setup:
|
|||
## Notes
|
||||
|
||||
- Admin image uploads create records in the `media` collection and store PocketBase file URLs in block JSON.
|
||||
- Draft preview writes current blocks to `sessionStorage` and opens `/preview` in an iframe.
|
||||
- Draft preview writes current blocks to `sessionStorage` and opens `/preview` in an iframe (same-origin on the admin subdomain).
|
||||
- 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.
|
||||
|
|
|
|||
25
app-admin/Dockerfile
Normal file
25
app-admin/Dockerfile
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
# syntax=docker/dockerfile:1.7
|
||||
|
||||
FROM node:22-alpine AS build
|
||||
WORKDIR /app
|
||||
ENV NPM_CONFIG_AUDIT=false \
|
||||
NPM_CONFIG_FUND=false \
|
||||
NPM_CONFIG_PROGRESS=false
|
||||
COPY app-admin/package*.json ./
|
||||
COPY packages/shared/package.json ./packages/shared/package.json
|
||||
RUN --mount=type=cache,target=/root/.npm npm ci --ignore-scripts --no-audit --no-fund
|
||||
COPY app-admin/ ./
|
||||
COPY packages/shared/ ./packages/shared/
|
||||
RUN npm run build
|
||||
|
||||
FROM node:22-alpine
|
||||
WORKDIR /app
|
||||
ENV NODE_ENV=production \
|
||||
NPM_CONFIG_AUDIT=false \
|
||||
NPM_CONFIG_FUND=false \
|
||||
NPM_CONFIG_PROGRESS=false
|
||||
COPY --from=build /app/build ./build
|
||||
COPY --from=build /app/package*.json ./
|
||||
RUN --mount=type=cache,target=/root/.npm npm ci --omit=dev --ignore-scripts --no-audit --no-fund
|
||||
EXPOSE 3001
|
||||
CMD ["node", "build"]
|
||||
1463
app/package-lock.json → app-admin/package-lock.json
generated
1463
app/package-lock.json → app-admin/package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"name": "app",
|
||||
"private": true,
|
||||
"name": "app-admin",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "vite build",
|
||||
|
|
@ -23,8 +23,8 @@
|
|||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@stripe/stripe-js": "^9.12.1",
|
||||
"@sveltejs/adapter-node": "^5.5.4",
|
||||
"@stripe/stripe-js": "^9.12.1",
|
||||
"@tailwindcss/vite": "^4.3.0",
|
||||
"@tiptap/core": "^3.23.4",
|
||||
"@tiptap/extension-link": "^3.23.4",
|
||||
|
|
@ -32,7 +32,6 @@
|
|||
"@tiptap/starter-kit": "^3.23.4",
|
||||
"daisyui": "^5.5.19",
|
||||
"pocketbase": "^0.26.9",
|
||||
"stripe": "^22.3.2",
|
||||
"svelte-tiptap": "^3.0.1",
|
||||
"tailwindcss": "^4.3.0",
|
||||
"uuid": "^14.0.0"
|
||||
0
app/src/app.d.ts → app-admin/src/app.d.ts
vendored
0
app/src/app.d.ts → app-admin/src/app.d.ts
vendored
|
|
@ -1,28 +1,27 @@
|
|||
import { redirect, type Handle } from '@sveltejs/kit';
|
||||
import { env } from '$env/dynamic/private';
|
||||
import { createPocketBase } from '$lib/pb';
|
||||
|
||||
export const handle: Handle = async ({ event, resolve }) => {
|
||||
event.locals.pb = createPocketBase(
|
||||
event.request.headers.get('cookie') ?? '',
|
||||
env.POCKETBASE_INTERNAL_URL
|
||||
);
|
||||
event.locals.user = event.locals.pb.authStore.record;
|
||||
|
||||
const path = event.url.pathname;
|
||||
const isAdminRoute = path.startsWith('/admin');
|
||||
const isLoginRoute = path === '/admin/login';
|
||||
const isAuthed = event.locals.pb.authStore.isValid;
|
||||
|
||||
if (isAdminRoute && !isLoginRoute && !isAuthed) {
|
||||
throw redirect(303, '/admin/login');
|
||||
}
|
||||
|
||||
if (isLoginRoute && isAuthed) {
|
||||
throw redirect(303, '/admin/pages');
|
||||
}
|
||||
|
||||
const response = await resolve(event);
|
||||
response.headers.append('set-cookie', event.locals.pb.authStore.exportToCookie({ sameSite: 'lax' }, 'pb_auth'));
|
||||
return response;
|
||||
};
|
||||
import { redirect, type Handle } from '@sveltejs/kit';
|
||||
import { env } from '$env/dynamic/private';
|
||||
import { createPocketBase } from '$lib/pb';
|
||||
|
||||
export const handle: Handle = async ({ event, resolve }) => {
|
||||
event.locals.pb = createPocketBase(
|
||||
event.request.headers.get('cookie') ?? '',
|
||||
env.POCKETBASE_INTERNAL_URL
|
||||
);
|
||||
event.locals.user = event.locals.pb.authStore.record;
|
||||
|
||||
const path = event.url.pathname;
|
||||
const isLoginRoute = path === '/login';
|
||||
const isAuthed = event.locals.pb.authStore.isValid;
|
||||
|
||||
if (!isLoginRoute && !isAuthed) {
|
||||
throw redirect(303, '/login');
|
||||
}
|
||||
|
||||
if (isLoginRoute && isAuthed) {
|
||||
throw redirect(303, '/pages');
|
||||
}
|
||||
|
||||
const response = await resolve(event);
|
||||
response.headers.append('set-cookie', event.locals.pb.authStore.exportToCookie({ sameSite: 'lax' }, 'pb_auth'));
|
||||
return response;
|
||||
};
|
||||
|
Before Width: | Height: | Size: 1.5 KiB After Width: | Height: | Size: 1.5 KiB |
1
app-admin/src/lib/calendar.ts
Normal file
1
app-admin/src/lib/calendar.ts
Normal file
|
|
@ -0,0 +1 @@
|
|||
export * from '$shared/calendar';
|
||||
37
app-admin/src/lib/pb.ts
Normal file
37
app-admin/src/lib/pb.ts
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
import PocketBase from 'pocketbase';
|
||||
import { env } from '$env/dynamic/public';
|
||||
import { browser } from '$app/environment';
|
||||
|
||||
export const pbUrl = env.PUBLIC_POCKETBASE_URL;
|
||||
|
||||
export function createPocketBase(authCookie?: string, url = pbUrl) {
|
||||
const pb = new PocketBase(url);
|
||||
pb.autoCancellation(false);
|
||||
|
||||
if (authCookie) {
|
||||
pb.authStore.loadFromCookie(authCookie, 'pb_auth');
|
||||
} else if (browser) {
|
||||
pb.authStore.loadFromCookie(document.cookie, 'pb_auth');
|
||||
}
|
||||
|
||||
return pb;
|
||||
}
|
||||
|
||||
export const pb = createPocketBase();
|
||||
|
||||
export function getFileUrl(collectionIdOrName: string, recordId: string, filename: string) {
|
||||
return `${pbUrl}/api/files/${collectionIdOrName}/${recordId}/${filename}`;
|
||||
}
|
||||
|
||||
export async function uploadMedia(file: File) {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
formData.append('alt', file.name.replace(/\.[^/.]+$/, '').replace(/[-_]/g, ' '));
|
||||
|
||||
const res = await fetch('/api/upload', { method: 'POST', body: formData });
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
throw new Error(err?.message || `Upload failed (${res.status})`);
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
1
app-admin/src/lib/types.ts
Normal file
1
app-admin/src/lib/types.ts
Normal file
|
|
@ -0,0 +1 @@
|
|||
export * from '$shared/types';
|
||||
16
app-admin/src/routes/+layout.server.ts
Normal file
16
app-admin/src/routes/+layout.server.ts
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
import { defaultColors } from '$lib/types';
|
||||
import type { LayoutServerLoad } from './$types';
|
||||
|
||||
async function getGlobal(pb: App.Locals['pb'], key: string, fallback: unknown) {
|
||||
try {
|
||||
const record = await pb.collection('globals').getFirstListItem(`key = "${key}"`);
|
||||
return record.data || fallback;
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
export const load: LayoutServerLoad = async ({ locals }) => {
|
||||
const colors = await getGlobal(locals.pb, 'colors', defaultColors);
|
||||
return { user: locals.user, colors };
|
||||
};
|
||||
|
|
@ -1,97 +1,126 @@
|
|||
<script lang="ts">
|
||||
let { children } = $props();
|
||||
let importStatus = $state<{ ok: boolean; message: string } | null>(null);
|
||||
let importing = $state(false);
|
||||
|
||||
async function handleExport() {
|
||||
try {
|
||||
const res = await fetch('/admin/api/export');
|
||||
if (!res.ok) throw new Error(`Export failed (${res.status})`);
|
||||
const blob = await res.blob();
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `cms-export-${new Date().toISOString().slice(0, 10)}.json`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
} catch (e) {
|
||||
importStatus = { ok: false, message: `Export error: ${e instanceof Error ? e.message : String(e)}` };
|
||||
}
|
||||
}
|
||||
|
||||
async function handleImport(event: Event) {
|
||||
const input = event.target as HTMLInputElement;
|
||||
const file = input.files?.[0];
|
||||
if (!file) return;
|
||||
|
||||
importing = true;
|
||||
importStatus = null;
|
||||
try {
|
||||
const text = await file.text();
|
||||
const json = JSON.parse(text);
|
||||
const res = await fetch('/admin/api/import', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(json)
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
throw new Error(err?.message || `Import failed (${res.status})`);
|
||||
}
|
||||
const result = await res.json();
|
||||
const msg = `Imported ${result.pagesImported} page(s), ${result.globalsImported} global(s), ${result.eventsImported || 0} event(s), ${result.imagesUploaded} image(s).`;
|
||||
importStatus = { ok: true, message: result.errors?.length ? msg + ` ${result.errors.length} error(s).` : msg };
|
||||
setTimeout(() => location.reload(), 1500);
|
||||
} catch (e) {
|
||||
importStatus = { ok: false, message: `Import error: ${e instanceof Error ? e.message : String(e)}` };
|
||||
} finally {
|
||||
importing = false;
|
||||
input.value = '';
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="min-h-screen bg-base-200">
|
||||
<div class="navbar bg-base-100 shadow-sm">
|
||||
<div class="flex-1">
|
||||
<a class="btn btn-ghost text-xl" href="/admin/pages">Massage CMS</a>
|
||||
</div>
|
||||
<div class="flex-none gap-2">
|
||||
<a class="btn btn-ghost" href="/admin/pages">Pages</a>
|
||||
<a class="btn btn-ghost" href="/admin/calendar">Calendar</a>
|
||||
<a class="btn btn-ghost" href="/admin/items">Items</a>
|
||||
<a class="btn btn-ghost" href="/admin/slots">Slots</a>
|
||||
<a class="btn btn-ghost" href="/admin/orders">Orders</a>
|
||||
<a class="btn btn-ghost" href="/admin/globals">Globals</a>
|
||||
<div class="dropdown dropdown-end">
|
||||
<button class="btn btn-ghost btn-sm" type="button" tabindex="0">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v2a2 2 0 002 2h12a2 2 0 002-2v-2M7 11l5 5 5-5M12 4v12" /></svg>
|
||||
Export/Import
|
||||
</button>
|
||||
<ul class="menu dropdown-content z-20 mt-2 w-48 rounded-box bg-base-100 p-2 shadow">
|
||||
<li><button type="button" onclick={handleExport}>Export all</button></li>
|
||||
<li>
|
||||
<button type="button" onclick={() => (document.getElementById('admin-import-file') as HTMLInputElement)?.click()} disabled={importing}>
|
||||
{importing ? 'Importing…' : 'Import'}
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<input id="admin-import-file" type="file" accept=".json" class="hidden" onchange={handleImport} />
|
||||
<form class="inline" method="POST" action="/admin/login?/logout">
|
||||
<button class="btn btn-outline btn-sm" type="submit">Logout</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
{#if importStatus}
|
||||
<div class="mx-auto max-w-7xl px-4 pt-2">
|
||||
<div class="alert" class:alert-success={importStatus.ok} class:alert-error={!importStatus.ok}>
|
||||
{importStatus.message}
|
||||
<button class="btn btn-ghost btn-xs" onclick={() => (importStatus = null)}>×</button>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
<main class="mx-auto max-w-7xl p-4 md:p-8">
|
||||
{@render children()}
|
||||
</main>
|
||||
</div>
|
||||
<script lang="ts">
|
||||
import '../app.css';
|
||||
import favicon from '$lib/assets/favicon.svg';
|
||||
import { createBasketStore, setBasketContext } from '$lib/basket.svelte';
|
||||
import { onMount } from 'svelte';
|
||||
|
||||
let { children, data } = $props();
|
||||
let importStatus = $state<{ ok: boolean; message: string } | null>(null);
|
||||
let importing = $state(false);
|
||||
|
||||
// One basket store per layout instance — provided to all children
|
||||
// (preview iframe block renderers). Never module-level state.
|
||||
// Admin doesn't have a real basket; pass null so the store starts empty.
|
||||
const basketStore = createBasketStore(null);
|
||||
setBasketContext(basketStore);
|
||||
|
||||
async function handleExport() {
|
||||
try {
|
||||
const res = await fetch('/api/export');
|
||||
if (!res.ok) throw new Error(`Export failed (${res.status})`);
|
||||
const blob = await res.blob();
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `cms-export-${new Date().toISOString().slice(0, 10)}.json`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
} catch (e) {
|
||||
importStatus = { ok: false, message: `Export error: ${e instanceof Error ? e.message : String(e)}` };
|
||||
}
|
||||
}
|
||||
|
||||
async function handleImport(event: Event) {
|
||||
const input = event.target as HTMLInputElement;
|
||||
const file = input.files?.[0];
|
||||
if (!file) return;
|
||||
|
||||
importing = true;
|
||||
importStatus = null;
|
||||
try {
|
||||
const text = await file.text();
|
||||
const json = JSON.parse(text);
|
||||
const res = await fetch('/api/import', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(json)
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
throw new Error(err?.message || `Import failed (${res.status})`);
|
||||
}
|
||||
const result = await res.json();
|
||||
const msg = `Imported ${result.pagesImported} page(s), ${result.globalsImported} global(s), ${result.eventsImported || 0} event(s), ${result.imagesUploaded} image(s).`;
|
||||
importStatus = { ok: true, message: result.errors?.length ? msg + ` ${result.errors.length} error(s).` : msg };
|
||||
setTimeout(() => location.reload(), 1500);
|
||||
} catch (e) {
|
||||
importStatus = { ok: false, message: `Import error: ${e instanceof Error ? e.message : String(e)}` };
|
||||
} finally {
|
||||
importing = false;
|
||||
input.value = '';
|
||||
}
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
// Apply saved colors so the preview iframe matches the public site.
|
||||
if (data.colors) {
|
||||
const root = document.documentElement;
|
||||
root.style.setProperty('--color-bg', data.colors.background);
|
||||
root.style.setProperty('--color-heading', data.colors.heading);
|
||||
root.style.setProperty('--color-subheading', data.colors.subheading);
|
||||
root.style.setProperty('--color-text', data.colors.text);
|
||||
root.style.setProperty('--color-primary', data.colors.primary);
|
||||
root.style.setProperty('--color-accent', data.colors.accent);
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
<link rel="icon" href={favicon} />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
</svelte:head>
|
||||
|
||||
<div class="min-h-screen bg-base-200">
|
||||
<div class="navbar bg-base-100 shadow-sm">
|
||||
<div class="flex-1">
|
||||
<a class="btn btn-ghost text-xl" href="/pages">Massage CMS</a>
|
||||
</div>
|
||||
<div class="flex-none gap-2">
|
||||
<a class="btn btn-ghost" href="/pages">Pages</a>
|
||||
<a class="btn btn-ghost" href="/calendar">Calendar</a>
|
||||
<a class="btn btn-ghost" href="/items">Items</a>
|
||||
<a class="btn btn-ghost" href="/slots">Slots</a>
|
||||
<a class="btn btn-ghost" href="/orders">Orders</a>
|
||||
<a class="btn btn-ghost" href="/globals">Globals</a>
|
||||
<div class="dropdown dropdown-end">
|
||||
<button class="btn btn-ghost btn-sm" type="button" tabindex="0">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v2a2 2 0 002 2h12a2 2 0 002-2v-2M7 11l5 5 5-5M12 4v12" /></svg>
|
||||
Export/Import
|
||||
</button>
|
||||
<ul class="menu dropdown-content z-20 mt-2 w-48 rounded-box bg-base-100 p-2 shadow">
|
||||
<li><button type="button" onclick={handleExport}>Export all</button></li>
|
||||
<li>
|
||||
<button type="button" onclick={() => (document.getElementById('admin-import-file') as HTMLInputElement)?.click()} disabled={importing}>
|
||||
{importing ? 'Importing…' : 'Import'}
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<input id="admin-import-file" type="file" accept=".json" class="hidden" onchange={handleImport} />
|
||||
<form class="inline" method="POST" action="/login?/logout">
|
||||
<button class="btn btn-outline btn-sm" type="submit">Logout</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
{#if importStatus}
|
||||
<div class="mx-auto max-w-7xl px-4 pt-2">
|
||||
<div class="alert" class:alert-success={importStatus.ok} class:alert-error={!importStatus.ok}>
|
||||
{importStatus.message}
|
||||
<button class="btn btn-ghost btn-xs" onclick={() => (importStatus = null)}>×</button>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
<main class="mx-auto max-w-7xl p-4 md:p-8">
|
||||
{@render children()}
|
||||
</main>
|
||||
</div>
|
||||
|
|
@ -27,15 +27,18 @@ export const GET: RequestHandler = async ({ locals }) => {
|
|||
for (const url of extractImageUrls(g)) allUrls.add(url);
|
||||
}
|
||||
|
||||
// Fetch each image as base64. Stored image URLs are public (http://localhost:8080)
|
||||
// but the app container must fetch them via the internal Docker network URL.
|
||||
const publicBase = env.PUBLIC_POCKETBASE_URL!;
|
||||
// Fetch each image as base64. Stored image URLs may use any public host
|
||||
// (e.g. http://localhost:8080 from before a domain migration, or
|
||||
// http://db.localhost:8080 after). The app container can only reach
|
||||
// PocketBase via the internal Docker network URL, so rewrite the host
|
||||
// of every matched URL to the internal base.
|
||||
const internalBase = env.POCKETBASE_INTERNAL_URL!;
|
||||
|
||||
const images: Record<string, string> = {};
|
||||
for (const url of allUrls) {
|
||||
try {
|
||||
const fetchUrl = url.startsWith(publicBase) ? url.replace(publicBase, internalBase) : url;
|
||||
// Replace the host (and optional port) with the internal base.
|
||||
const fetchUrl = url.replace(/^[a-z]+:\/\/[^/]+/, internalBase);
|
||||
const key = urlToKey(url);
|
||||
images[key] = await fetchImageAsBase64(fetchUrl);
|
||||
} catch (e) {
|
||||
|
|
@ -58,7 +58,7 @@
|
|||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
formData.append('alt', file.name.replace(/\.[^/.]+$/, '').replace(/[-_]/g, ' '));
|
||||
const res = await fetch('/admin/api/upload', { method: 'POST', body: formData });
|
||||
const res = await fetch('/api/upload', { method: 'POST', body: formData });
|
||||
if (!res.ok) throw new Error(`Upload failed (${res.status})`);
|
||||
const result = await res.json();
|
||||
draft = { ...draft, image: result.record.id, imageUrl: result.url };
|
||||
|
|
@ -18,10 +18,10 @@ export const actions: Actions = {
|
|||
return fail(400, { message: 'Invalid email or password.' });
|
||||
}
|
||||
|
||||
throw redirect(303, '/admin/pages');
|
||||
throw redirect(303, '/pages');
|
||||
},
|
||||
logout: async ({ locals }) => {
|
||||
locals.pb.authStore.clear();
|
||||
throw redirect(303, '/admin/login');
|
||||
throw redirect(303, '/login');
|
||||
}
|
||||
};
|
||||
|
|
@ -14,7 +14,7 @@ export const actions: Actions = {
|
|||
if (!slug || !title) return fail(400, { message: 'Slug and title are required.' });
|
||||
|
||||
await locals.pb.collection('pages').create({ slug, title, blocks: [], published: false });
|
||||
throw redirect(303, `/admin/pages/${slug}`);
|
||||
throw redirect(303, `/pages/${slug}`);
|
||||
},
|
||||
toggle: async ({ request, locals }) => {
|
||||
const data = await request.formData();
|
||||
|
|
@ -28,8 +28,8 @@
|
|||
<td>{page.title}</td>
|
||||
<td><span class="badge" class:badge-success={page.published}>{page.published ? 'Published' : 'Draft'}</span></td>
|
||||
<td class="flex justify-end gap-2">
|
||||
<a class="btn btn-sm" href={`/admin/pages/${page.slug}`}>Edit</a>
|
||||
<a class="btn btn-sm" href={page.slug === 'home' ? '/' : `/${page.slug}`} target="_blank">Preview</a>
|
||||
<a class="btn btn-sm" href={`/pages/${page.slug}`}>Edit</a>
|
||||
<a class="btn btn-sm" href={`${import.meta.env.VITE_PUBLIC_SITE_URL}/${page.slug === 'home' ? '' : page.slug}`} target="_blank">Preview</a>
|
||||
<form method="POST" action="?/toggle">
|
||||
<input type="hidden" name="id" value={page.id} />
|
||||
<input type="hidden" name="published" value={page.published} />
|
||||
|
|
@ -25,6 +25,6 @@ export const actions: Actions = {
|
|||
if (!slug || !title) return fail(400, { message: 'Slug and title are required.' });
|
||||
|
||||
await locals.pb.collection('pages').update(id, { slug, title, blocks, ...(publish ? { published: true } : {}) });
|
||||
throw redirect(303, `/admin/pages/${slug}`);
|
||||
throw redirect(303, `/pages/${slug}`);
|
||||
}
|
||||
};
|
||||
|
|
@ -7,7 +7,10 @@ const config = {
|
|||
runes: ({ filename }) => (filename.split(/[/\\]/).includes('node_modules') ? undefined : true)
|
||||
},
|
||||
kit: {
|
||||
adapter: adapter()
|
||||
adapter: adapter(),
|
||||
alias: {
|
||||
$shared: '../packages/shared/src'
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
14
app-admin/tsconfig.json
Normal file
14
app-admin/tsconfig.json
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
{
|
||||
"extends": "./.svelte-kit/tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"allowJs": true,
|
||||
"checkJs": true,
|
||||
"esModuleInterop": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"resolveJsonModule": true,
|
||||
"skipLibCheck": true,
|
||||
"sourceMap": true,
|
||||
"strict": true,
|
||||
"moduleResolution": "bundler"
|
||||
}
|
||||
}
|
||||
1
app-public/.npmrc
Normal file
1
app-public/.npmrc
Normal file
|
|
@ -0,0 +1 @@
|
|||
engine-strict=true
|
||||
|
|
@ -1,23 +1,25 @@
|
|||
# syntax=docker/dockerfile:1.7
|
||||
|
||||
FROM node:22-alpine AS build
|
||||
WORKDIR /app
|
||||
ENV NPM_CONFIG_AUDIT=false \
|
||||
NPM_CONFIG_FUND=false \
|
||||
NPM_CONFIG_PROGRESS=false
|
||||
COPY app/package*.json ./
|
||||
RUN --mount=type=cache,target=/root/.npm npm ci --ignore-scripts --no-audit --no-fund
|
||||
COPY app/ ./
|
||||
RUN npm run build
|
||||
|
||||
FROM node:22-alpine
|
||||
WORKDIR /app
|
||||
ENV NODE_ENV=production \
|
||||
NPM_CONFIG_AUDIT=false \
|
||||
NPM_CONFIG_FUND=false \
|
||||
NPM_CONFIG_PROGRESS=false
|
||||
COPY --from=build /app/build ./build
|
||||
COPY --from=build /app/package*.json ./
|
||||
RUN --mount=type=cache,target=/root/.npm npm ci --omit=dev --ignore-scripts --no-audit --no-fund
|
||||
EXPOSE 3000
|
||||
CMD ["node", "build"]
|
||||
# syntax=docker/dockerfile:1.7
|
||||
|
||||
FROM node:22-alpine AS build
|
||||
WORKDIR /app
|
||||
ENV NPM_CONFIG_AUDIT=false \
|
||||
NPM_CONFIG_FUND=false \
|
||||
NPM_CONFIG_PROGRESS=false
|
||||
COPY app-public/package*.json ./
|
||||
COPY packages/shared/package.json ./packages/shared/package.json
|
||||
RUN --mount=type=cache,target=/root/.npm npm ci --ignore-scripts --no-audit --no-fund
|
||||
COPY app-public/ ./
|
||||
COPY packages/shared/ ./packages/shared/
|
||||
RUN npm run build
|
||||
|
||||
FROM node:22-alpine
|
||||
WORKDIR /app
|
||||
ENV NODE_ENV=production \
|
||||
NPM_CONFIG_AUDIT=false \
|
||||
NPM_CONFIG_FUND=false \
|
||||
NPM_CONFIG_PROGRESS=false
|
||||
COPY --from=build /app/build ./build
|
||||
COPY --from=build /app/package*.json ./
|
||||
RUN --mount=type=cache,target=/root/.npm npm ci --omit=dev --ignore-scripts --no-audit --no-fund
|
||||
EXPOSE 3000
|
||||
CMD ["node", "build"]
|
||||
2476
app-public/package-lock.json
generated
Normal file
2476
app-public/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load diff
30
app-public/package.json
Normal file
30
app-public/package.json
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
{
|
||||
"name": "app-public",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "vite build",
|
||||
"prepare": "svelte-kit sync || echo ''",
|
||||
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
|
||||
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@sveltejs/kit": "^2.57.0",
|
||||
"@sveltejs/vite-plugin-svelte": "^7.0.0",
|
||||
"@types/node": "^25.8.0",
|
||||
"svelte": "^5.55.2",
|
||||
"svelte-check": "^4.4.6",
|
||||
"typescript": "^6.0.2",
|
||||
"vite": "^8.0.7"
|
||||
},
|
||||
"dependencies": {
|
||||
"@stripe/stripe-js": "^9.12.1",
|
||||
"@sveltejs/adapter-node": "^5.5.4",
|
||||
"@tailwindcss/vite": "^4.3.0",
|
||||
"daisyui": "^5.5.19",
|
||||
"pocketbase": "^0.26.9",
|
||||
"stripe": "^22.3.2",
|
||||
"tailwindcss": "^4.3.0"
|
||||
}
|
||||
}
|
||||
140
app-public/src/app.css
Normal file
140
app-public/src/app.css
Normal file
|
|
@ -0,0 +1,140 @@
|
|||
@import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=Playfair+Display:wght@600;700&display=swap');
|
||||
@import 'tailwindcss';
|
||||
@plugin 'daisyui' {
|
||||
themes: light --default;
|
||||
}
|
||||
|
||||
@theme {
|
||||
--font-sans: 'DM Sans', ui-sans-serif, system-ui, sans-serif;
|
||||
--font-serif: 'Playfair Display', Georgia, serif;
|
||||
--color-warm: var(--color-bg, #faf8f5);
|
||||
--color-charcoal: var(--color-heading, #2c2c2c);
|
||||
--color-sage: var(--color-primary, #8a9a7b);
|
||||
--color-sage-dark: color-mix(in srgb, var(--color-primary, #8a9a7b) 80%, #000);
|
||||
--color-terracotta: var(--color-accent, #c9825f);
|
||||
}
|
||||
|
||||
@keyframes shrink {
|
||||
from { scale: 0 1; }
|
||||
to { scale: 1 1; }
|
||||
}
|
||||
|
||||
.delete-fill {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: transparent;
|
||||
transform-origin: left;
|
||||
}
|
||||
|
||||
.delete-fill.animating {
|
||||
animation: shrink 1s ease-in-out forwards;
|
||||
background: var(--error, #f43f5e);
|
||||
}
|
||||
|
||||
.btn.delete-holding {
|
||||
color: white !important;
|
||||
}
|
||||
|
||||
.btn.delete-holding .text-error {
|
||||
color: white !important;
|
||||
}
|
||||
|
||||
:root {
|
||||
--fg-heading: var(--color-heading, #2c2c2c);
|
||||
--fg-subheading: var(--color-subheading, #4a4a4a);
|
||||
--fg-body: var(--color-text, #2c2c2c);
|
||||
background: var(--color-bg, #faf8f5);
|
||||
color: var(--fg-body);
|
||||
font-family: 'DM Sans', ui-sans-serif, system-ui, sans-serif;
|
||||
}
|
||||
|
||||
/* ── Foreground colour utilities (set per-block via BackgroundWrapper) ── */
|
||||
.text-fg-body { color: var(--fg-body, #2c2c2c); }
|
||||
.text-fg-body\/85 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 85%, transparent); }
|
||||
.text-fg-body\/80 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 80%, transparent); }
|
||||
.text-fg-body\/75 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 75%, transparent); }
|
||||
.text-fg-body\/70 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 70%, transparent); }
|
||||
.text-fg-body\/60 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 60%, transparent); }
|
||||
.text-fg-heading { color: var(--fg-heading, #2c2c2c); }
|
||||
.text-fg-subheading { color: var(--fg-subheading, #4a4a4a); }
|
||||
.text-fg-subheading\/85 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 85%, transparent); }
|
||||
.text-fg-subheading\/80 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 80%, transparent); }
|
||||
.text-fg-subheading\/75 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 75%, transparent); }
|
||||
.text-fg-subheading\/70 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 70%, transparent); }
|
||||
.text-fg-subheading\/60 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 60%, transparent); }
|
||||
|
||||
body {
|
||||
min-height: 100vh;
|
||||
margin: 0;
|
||||
background:
|
||||
radial-gradient(circle at top left, rgba(var(--color-accent-rgb, 201, 130, 95), 0.1), transparent 36rem),
|
||||
var(--color-bg, #faf8f5);
|
||||
}
|
||||
|
||||
h1,
|
||||
h2,
|
||||
h3,
|
||||
h4 {
|
||||
font-family: 'Playfair Display', Georgia, serif;
|
||||
color: var(--fg-heading, #2c2c2c);
|
||||
}
|
||||
|
||||
.prose-wellness p {
|
||||
margin: 0.75rem 0;
|
||||
line-height: 1.8;
|
||||
}
|
||||
|
||||
.prose-wellness h2 {
|
||||
margin: 1.25rem 0 0.5rem;
|
||||
font-size: clamp(2rem, 4vw, 3.25rem);
|
||||
line-height: 1.05;
|
||||
}
|
||||
|
||||
.prose-wellness h3 {
|
||||
margin: 1rem 0 0.5rem;
|
||||
font-size: 1.6rem;
|
||||
}
|
||||
|
||||
.prose-wellness ul {
|
||||
list-style: disc;
|
||||
padding-left: 1.5rem;
|
||||
}
|
||||
|
||||
.prose-wellness a {
|
||||
color: color-mix(in srgb, var(--color-primary, #8a9a7b) 90%, #000);
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 3px;
|
||||
}
|
||||
|
||||
/* ── Scroll-reveal animations ── */
|
||||
.reveal {
|
||||
opacity: 0;
|
||||
transform: translateY(30px);
|
||||
transition:
|
||||
opacity 0.7s cubic-bezier(0.25, 0.1, 0.25, 1),
|
||||
transform 0.7s cubic-bezier(0.25, 0.1, 0.25, 1);
|
||||
}
|
||||
|
||||
.reveal-visible {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
/* ── Hero fade-in stagger ── */
|
||||
.animate-fade-in {
|
||||
opacity: 0;
|
||||
transform: translateY(20px);
|
||||
animation: fadeInUp 0.8s cubic-bezier(0.25, 0.1, 0.25, 1) forwards;
|
||||
}
|
||||
|
||||
@keyframes fadeInUp {
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
/* ── Smooth scroll ── */
|
||||
html {
|
||||
scroll-behavior: smooth;
|
||||
}
|
||||
18
app-public/src/app.d.ts
vendored
Normal file
18
app-public/src/app.d.ts
vendored
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
// See https://svelte.dev/docs/kit/types#app.d.ts
|
||||
// for information about these interfaces
|
||||
import type PocketBase from 'pocketbase';
|
||||
|
||||
declare global {
|
||||
namespace App {
|
||||
// interface Error {}
|
||||
interface Locals {
|
||||
pb: PocketBase;
|
||||
user: import('pocketbase').AuthRecord | null;
|
||||
}
|
||||
// interface PageData {}
|
||||
// interface PageState {}
|
||||
// interface Platform {}
|
||||
}
|
||||
}
|
||||
|
||||
export {};
|
||||
12
app-public/src/app.html
Normal file
12
app-public/src/app.html
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="text-scale" content="scale" />
|
||||
%sveltekit.head%
|
||||
</head>
|
||||
<body data-sveltekit-preload-data="hover">
|
||||
<div style="display: contents">%sveltekit.body%</div>
|
||||
</body>
|
||||
</html>
|
||||
15
app-public/src/hooks.server.ts
Normal file
15
app-public/src/hooks.server.ts
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
import type { Handle } from '@sveltejs/kit';
|
||||
import { env } from '$env/dynamic/private';
|
||||
import { createPocketBase } from '$lib/pb';
|
||||
|
||||
export const handle: Handle = async ({ event, resolve }) => {
|
||||
event.locals.pb = createPocketBase(
|
||||
event.request.headers.get('cookie') ?? '',
|
||||
env.POCKETBASE_INTERNAL_URL
|
||||
);
|
||||
event.locals.user = event.locals.pb.authStore.record;
|
||||
|
||||
const response = await resolve(event);
|
||||
response.headers.append('set-cookie', event.locals.pb.authStore.exportToCookie({ sameSite: 'lax' }, 'pb_auth'));
|
||||
return response;
|
||||
};
|
||||
1
app-public/src/lib/assets/favicon.svg
Normal file
1
app-public/src/lib/assets/favicon.svg
Normal file
|
|
@ -0,0 +1 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" width="107" height="128" viewBox="0 0 107 128"><title>svelte-logo</title><path d="M94.157 22.819c-10.4-14.885-30.94-19.297-45.792-9.835L22.282 29.608A29.92 29.92 0 0 0 8.764 49.65a31.5 31.5 0 0 0 3.108 20.231 30 30 0 0 0-4.477 11.183 31.9 31.9 0 0 0 5.448 24.116c10.402 14.887 30.942 19.297 45.791 9.835l26.083-16.624A29.92 29.92 0 0 0 98.235 78.35a31.53 31.53 0 0 0-3.105-20.232 30 30 0 0 0 4.474-11.182 31.88 31.88 0 0 0-5.447-24.116" style="fill:#ff3e00"/><path d="M45.817 106.582a20.72 20.72 0 0 1-22.237-8.243 19.17 19.17 0 0 1-3.277-14.503 18 18 0 0 1 .624-2.435l.49-1.498 1.337.981a33.6 33.6 0 0 0 10.203 5.098l.97.294-.09.968a5.85 5.85 0 0 0 1.052 3.878 6.24 6.24 0 0 0 6.695 2.485 5.8 5.8 0 0 0 1.603-.704L69.27 76.28a5.43 5.43 0 0 0 2.45-3.631 5.8 5.8 0 0 0-.987-4.371 6.24 6.24 0 0 0-6.698-2.487 5.7 5.7 0 0 0-1.6.704l-9.953 6.345a19 19 0 0 1-5.296 2.326 20.72 20.72 0 0 1-22.237-8.243 19.17 19.17 0 0 1-3.277-14.502 17.99 17.99 0 0 1 8.13-12.052l26.081-16.623a19 19 0 0 1 5.3-2.329 20.72 20.72 0 0 1 22.237 8.243 19.17 19.17 0 0 1 3.277 14.503 18 18 0 0 1-.624 2.435l-.49 1.498-1.337-.98a33.6 33.6 0 0 0-10.203-5.1l-.97-.294.09-.968a5.86 5.86 0 0 0-1.052-3.878 6.24 6.24 0 0 0-6.696-2.485 5.8 5.8 0 0 0-1.602.704L37.73 51.72a5.42 5.42 0 0 0-2.449 3.63 5.79 5.79 0 0 0 .986 4.372 6.24 6.24 0 0 0 6.698 2.486 5.8 5.8 0 0 0 1.602-.704l9.952-6.342a19 19 0 0 1 5.295-2.328 20.72 20.72 0 0 1 22.237 8.242 19.17 19.17 0 0 1 3.277 14.503 18 18 0 0 1-8.13 12.053l-26.081 16.622a19 19 0 0 1-5.3 2.328" style="fill:#fff"/></svg>
|
||||
|
After Width: | Height: | Size: 1.5 KiB |
94
app-public/src/lib/basket.svelte.ts
Normal file
94
app-public/src/lib/basket.svelte.ts
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
import { getContext, setContext } from 'svelte';
|
||||
import type { Basket, BasketLine } from '$lib/types';
|
||||
|
||||
const BASKET_KEY = 'basket';
|
||||
|
||||
export type BasketStore = ReturnType<typeof createBasketStore>;
|
||||
|
||||
export function createBasketStore(initial: Basket | null) {
|
||||
let lines = $state<BasketLine[]>(initial?.lines ?? []);
|
||||
let status = $state<Basket['status']>(initial?.status ?? 'active');
|
||||
|
||||
const total = $derived(
|
||||
lines.reduce((sum, line) => sum + (line.itemPrice ?? 0) * line.quantity, 0)
|
||||
);
|
||||
const count = $derived(lines.reduce((sum, line) => sum + line.quantity, 0));
|
||||
|
||||
async function callApi(body: Record<string, unknown>): Promise<Basket | null> {
|
||||
const res = await fetch('/api/basket', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body)
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
throw new Error(err?.message || `Basket request failed (${res.status})`);
|
||||
}
|
||||
const data = await res.json();
|
||||
return data.basket as Basket | null;
|
||||
}
|
||||
|
||||
function applyBasket(basket: Basket | null) {
|
||||
lines = basket?.lines ?? [];
|
||||
status = basket?.status ?? 'active';
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
const res = await fetch('/api/basket');
|
||||
if (!res.ok) return;
|
||||
const data = await res.json();
|
||||
applyBasket(data.basket);
|
||||
}
|
||||
|
||||
/** Overwrite local state from server-provided layout data. */
|
||||
function syncFrom(basket: Basket | null) {
|
||||
applyBasket(basket);
|
||||
}
|
||||
|
||||
async function addItemLine(itemId: string, quantity = 1) {
|
||||
applyBasket(await callApi({ action: 'add_item', itemId, quantity }));
|
||||
}
|
||||
|
||||
async function addSlotLine(slotId: string) {
|
||||
applyBasket(await callApi({ action: 'add_slot', slotId }));
|
||||
}
|
||||
|
||||
async function updateQuantity(lineId: string, quantity: number) {
|
||||
applyBasket(await callApi({ action: 'update_quantity', lineId, quantity }));
|
||||
}
|
||||
|
||||
async function removeLine(lineId: string) {
|
||||
applyBasket(await callApi({ action: 'remove_line', lineId }));
|
||||
}
|
||||
|
||||
return {
|
||||
get lines() {
|
||||
return lines;
|
||||
},
|
||||
get total() {
|
||||
return total;
|
||||
},
|
||||
get count() {
|
||||
return count;
|
||||
},
|
||||
get status() {
|
||||
return status;
|
||||
},
|
||||
refresh,
|
||||
syncFrom,
|
||||
addItemLine,
|
||||
addSlotLine,
|
||||
updateQuantity,
|
||||
removeLine
|
||||
};
|
||||
}
|
||||
|
||||
export function setBasketContext(store: BasketStore) {
|
||||
setContext(BASKET_KEY, store);
|
||||
}
|
||||
|
||||
export function getBasketContext(): BasketStore {
|
||||
const store = getContext<BasketStore>(BASKET_KEY);
|
||||
if (!store) throw new Error('Basket store not found in context — is this component inside the public layout?');
|
||||
return store;
|
||||
}
|
||||
54
app-public/src/lib/blocks/BackgroundWrapper.svelte
Normal file
54
app-public/src/lib/blocks/BackgroundWrapper.svelte
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
<script lang="ts">
|
||||
import type { BlockBackground, BlockForeground } from '$lib/types';
|
||||
|
||||
let {
|
||||
background = { type: 'none', color: '', imageUrl: '', attachment: 'scroll', overlay: false, overlayOpacity: 40 } satisfies BlockBackground,
|
||||
foreground = {} as BlockForeground,
|
||||
children
|
||||
} = $props<{
|
||||
background?: BlockBackground;
|
||||
foreground?: BlockForeground;
|
||||
children?: import('svelte').Snippet;
|
||||
}>();
|
||||
|
||||
function bgStyle() {
|
||||
const parts: string[] = [];
|
||||
if (background.type === 'color' && background.color) {
|
||||
parts.push(`background-color: ${background.color};`);
|
||||
}
|
||||
if (background.type === 'image' && background.imageUrl) {
|
||||
parts.push(`background-image: url(${background.imageUrl});`);
|
||||
parts.push(`background-size: cover;`);
|
||||
parts.push(`background-position: center;`);
|
||||
parts.push(`background-repeat: no-repeat;`);
|
||||
parts.push(`background-attachment: ${background.attachment};`);
|
||||
}
|
||||
return parts.join(' ');
|
||||
}
|
||||
|
||||
function fgStyle() {
|
||||
const parts: string[] = [];
|
||||
if (foreground.headingColor) {
|
||||
parts.push(`--fg-heading: ${foreground.headingColor};`);
|
||||
}
|
||||
if (foreground.textColor) {
|
||||
parts.push(`--fg-body: ${foreground.textColor};`);
|
||||
}
|
||||
if (foreground.subheadingColor) {
|
||||
parts.push(`--fg-subheading: ${foreground.subheadingColor};`);
|
||||
}
|
||||
return parts.join(' ');
|
||||
}
|
||||
</script>
|
||||
|
||||
<div style={bgStyle() + ' ' + fgStyle()} class="relative">
|
||||
{#if background.type === 'image' && background.overlay && background.imageUrl}
|
||||
<div
|
||||
class="pointer-events-none absolute inset-0"
|
||||
style={`background-color: rgba(0,0,0,${background.overlayOpacity / 100});`}
|
||||
></div>
|
||||
{/if}
|
||||
<div class="relative z-10">
|
||||
{@render children()}
|
||||
</div>
|
||||
</div>
|
||||
55
app-public/src/lib/blocks/BlockRenderer.svelte
Normal file
55
app-public/src/lib/blocks/BlockRenderer.svelte
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
<script lang="ts">
|
||||
import type { CalendarEventRecord, ContentBlock, BlockBackground, BlockForeground, ItemRecord, SlotRecord } from '$lib/types';
|
||||
import BackgroundWrapper from './BackgroundWrapper.svelte';
|
||||
import TextBlock from './TextBlock.svelte';
|
||||
import ImageTextBlock from './ImageTextBlock.svelte';
|
||||
import TimelineBlock from './TimelineBlock.svelte';
|
||||
import HeroBlock from './HeroBlock.svelte';
|
||||
import ButtonBlock from './ButtonBlock.svelte';
|
||||
import SpacerBlock from './SpacerBlock.svelte';
|
||||
import TestimonialsBlock from './TestimonialsBlock.svelte';
|
||||
import UpcomingCalendarBlock from './UpcomingCalendarBlock.svelte';
|
||||
import ShopBlock from './ShopBlock.svelte';
|
||||
import CheckoutBlock from './CheckoutBlock.svelte';
|
||||
|
||||
let { blocks = [], calendarEvents = [], items = [], slots = [] } = $props<{
|
||||
blocks: ContentBlock[];
|
||||
calendarEvents?: CalendarEventRecord[];
|
||||
items?: ItemRecord[];
|
||||
slots?: SlotRecord[];
|
||||
}>();
|
||||
|
||||
function getBg(block: ContentBlock): BlockBackground {
|
||||
return (block.data._background as BlockBackground) || { type: 'none', color: '', imageUrl: '', attachment: 'scroll', overlay: false, overlayOpacity: 40 };
|
||||
}
|
||||
|
||||
function getFg(block: ContentBlock): BlockForeground {
|
||||
return (block.data._foreground as BlockForeground) || {};
|
||||
}
|
||||
</script>
|
||||
|
||||
{#each blocks as block (block.id)}
|
||||
<BackgroundWrapper background={getBg(block)} foreground={getFg(block)}>
|
||||
{#if block.type === 'text'}
|
||||
<TextBlock data={block.data} />
|
||||
{:else if block.type === 'image_text'}
|
||||
<ImageTextBlock data={block.data} />
|
||||
{:else if block.type === 'timeline'}
|
||||
<TimelineBlock data={block.data} />
|
||||
{:else if block.type === 'hero'}
|
||||
<HeroBlock data={block.data} />
|
||||
{:else if block.type === 'button'}
|
||||
<ButtonBlock data={block.data} />
|
||||
{:else if block.type === 'spacer'}
|
||||
<SpacerBlock data={block.data} />
|
||||
{:else if block.type === 'testimonials'}
|
||||
<TestimonialsBlock data={block.data} />
|
||||
{:else if block.type === 'upcoming_calendar'}
|
||||
<UpcomingCalendarBlock data={block.data} events={calendarEvents} />
|
||||
{:else if block.type === 'shop'}
|
||||
<ShopBlock data={block.data} {items} {slots} />
|
||||
{:else if block.type === 'checkout'}
|
||||
<CheckoutBlock data={block.data} />
|
||||
{/if}
|
||||
</BackgroundWrapper>
|
||||
{/each}
|
||||
26
app-public/src/lib/blocks/ButtonBlock.svelte
Normal file
26
app-public/src/lib/blocks/ButtonBlock.svelte
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
<script lang="ts">
|
||||
let { data } = $props<{ data: Record<string, any> }>();
|
||||
|
||||
const alignmentClasses: Record<string, string> = {
|
||||
left: 'justify-start',
|
||||
center: 'justify-center',
|
||||
right: 'justify-end'
|
||||
};
|
||||
|
||||
const sizeClasses: Record<string, string> = {
|
||||
xs: 'btn-xs',
|
||||
sm: 'btn-sm',
|
||||
md: '',
|
||||
lg: 'btn-lg'
|
||||
};
|
||||
</script>
|
||||
|
||||
<div class="flex {alignmentClasses[data.alignment] || 'justify-center'}">
|
||||
<a
|
||||
href={data.href || '#'}
|
||||
class="btn btn-{data.variant || 'primary'} {sizeClasses[data.size] || ''}"
|
||||
style={data.color ? `background-color: ${data.color}; border-color: ${data.color};` : ''}
|
||||
>
|
||||
{data.label || 'Button'}
|
||||
</a>
|
||||
</div>
|
||||
402
app-public/src/lib/blocks/CheckoutBlock.svelte
Normal file
402
app-public/src/lib/blocks/CheckoutBlock.svelte
Normal file
|
|
@ -0,0 +1,402 @@
|
|||
<script lang="ts">
|
||||
import { browser } from '$app/environment';
|
||||
import { goto } from '$app/navigation';
|
||||
import type { CheckoutBlockData } from '$lib/types';
|
||||
import { getBasketContext } from '$lib/basket.svelte';
|
||||
import { loadStripe } from '$lib/stripe-client';
|
||||
import type { Stripe, StripeElements, StripePaymentElement } from '@stripe/stripe-js';
|
||||
|
||||
let { data = {} } = $props<{ data: CheckoutBlockData }>();
|
||||
|
||||
const basket = getBasketContext();
|
||||
|
||||
const customer = $state({ name: '', email: '', phone: '', notes: '' });
|
||||
let payState = $state<'idle' | 'creating' | 'ready' | 'confirming' | 'error'>('idle');
|
||||
let errorMsg = $state('');
|
||||
|
||||
let paymentDiv = $state<HTMLDivElement | null>(null);
|
||||
let stripe: Stripe | null = null;
|
||||
let elements: StripeElements | null = null;
|
||||
let paymentElement: StripePaymentElement | null = null;
|
||||
let mountedForClientSecret: string | null = null;
|
||||
|
||||
// Tracks lines that have an update/remove request in flight, to disable their controls.
|
||||
let pendingLines = $state<Set<string>>(new Set());
|
||||
|
||||
// Reset the mounted Payment Element back to 'idle' when the basket changes
|
||||
// after the intent was created, so a new intent is made with the new total.
|
||||
let lastSig = '';
|
||||
let basketChanged = $state(false);
|
||||
$effect(() => {
|
||||
const sig = basket.lines.map((l) => `${l.id}:${l.quantity}`).join('|') + `@${basket.total}`;
|
||||
if (lastSig && sig !== lastSig && (payState === 'ready' || payState === 'creating')) {
|
||||
resetPayment();
|
||||
basketChanged = true;
|
||||
} else if (sig === lastSig) {
|
||||
basketChanged = false;
|
||||
}
|
||||
lastSig = sig;
|
||||
});
|
||||
|
||||
const currency = new Intl.NumberFormat(undefined, { style: 'currency', currency: 'EUR' });
|
||||
const payLabel = $derived(
|
||||
payState === 'confirming'
|
||||
? 'Confirming…'
|
||||
: payState === 'creating'
|
||||
? 'Preparing payment…'
|
||||
: `Pay ${currency.format(basket.total)}`
|
||||
);
|
||||
|
||||
function formatSlotTime(iso: string) {
|
||||
return new Date(iso).toLocaleString(undefined, {
|
||||
weekday: 'short',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
});
|
||||
}
|
||||
|
||||
function resetPayment() {
|
||||
paymentElement?.unmount();
|
||||
paymentElement = null;
|
||||
elements = null;
|
||||
mountedForClientSecret = null;
|
||||
payState = 'idle';
|
||||
}
|
||||
|
||||
function validateCustomer(): boolean {
|
||||
if (!customer.name.trim() || !customer.email.trim()) {
|
||||
errorMsg = 'Please fill in your name and email address.';
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
async function startPayment() {
|
||||
errorMsg = '';
|
||||
basketChanged = false;
|
||||
if (!validateCustomer()) return;
|
||||
|
||||
payState = 'creating';
|
||||
try {
|
||||
// Refresh from server first — slot holds may have lapsed (10-min TTL)
|
||||
// and the client store would still show stale lines. The server
|
||||
// re-reserves any slot that is still held, so a service won't vanish
|
||||
// just because its hold expired while you were filling in this form.
|
||||
const slotLinesBefore = basket.lines.filter((l) => l.lineType === 'slot');
|
||||
await basket.refresh();
|
||||
|
||||
const lostSlots = slotLinesBefore.filter(
|
||||
(l) => !basket.lines.some((nl) => nl.id === l.id)
|
||||
);
|
||||
if (basket.lines.length === 0) {
|
||||
throw new Error('Your basket is empty — a time slot you selected may have expired. Please pick a slot from the shop and try again.');
|
||||
}
|
||||
if (lostSlots.length) {
|
||||
const names = lostSlots.map((l) => l.itemName).filter(Boolean).join(', ');
|
||||
throw new Error(
|
||||
names
|
||||
? `Your time slot for ${names} is no longer available (it may have expired or been booked by someone else). Please pick another slot from the shop.`
|
||||
: 'A time slot in your basket is no longer available — please pick another slot from the shop.'
|
||||
);
|
||||
}
|
||||
|
||||
const res = await fetch('/api/checkout/create-intent', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ...customer })
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
throw new Error(
|
||||
err?.message ||
|
||||
`Could not start payment (${res.status}). If you booked a time slot, its hold may have expired — please pick it again from the shop section.`
|
||||
);
|
||||
}
|
||||
const { clientSecret } = await res.json();
|
||||
|
||||
stripe = await loadStripe();
|
||||
if (!stripe) throw new Error('Payment system failed to load. Please refresh and try again.');
|
||||
|
||||
if (mountedForClientSecret !== clientSecret) {
|
||||
resetPayment();
|
||||
elements = stripe.elements({
|
||||
clientSecret,
|
||||
appearance: {
|
||||
theme: 'flat',
|
||||
variables: {
|
||||
colorPrimary: '#8a9a7b',
|
||||
colorBackground: '#ffffff',
|
||||
colorText: '#2c2c2c',
|
||||
colorDanger: '#c9825f',
|
||||
fontFamily: 'DM Sans, sans-serif',
|
||||
borderRadius: '12px'
|
||||
}
|
||||
}
|
||||
});
|
||||
paymentElement = elements.create('payment');
|
||||
if (browser && paymentDiv) {
|
||||
paymentElement.mount(paymentDiv);
|
||||
mountedForClientSecret = clientSecret;
|
||||
}
|
||||
}
|
||||
payState = 'ready';
|
||||
} catch (e) {
|
||||
errorMsg = e instanceof Error ? e.message : 'Something went wrong. Please try again.';
|
||||
payState = 'idle';
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmPayment() {
|
||||
if (!stripe || !elements || !mountedForClientSecret) return;
|
||||
errorMsg = '';
|
||||
payState = 'confirming';
|
||||
|
||||
const { error } = await stripe.confirmPayment({
|
||||
elements,
|
||||
confirmParams: {
|
||||
return_url: window.location.origin + '/checkout/return',
|
||||
receipt_email: customer.email
|
||||
},
|
||||
redirect: 'if_required'
|
||||
});
|
||||
|
||||
if (error) {
|
||||
errorMsg = error.message ?? 'Payment failed. Please try again.';
|
||||
payState = 'ready';
|
||||
} else {
|
||||
const intentId = mountedForClientSecret.split('_secret_')[0];
|
||||
goto('/checkout/return?payment_intent=' + encodeURIComponent(intentId));
|
||||
}
|
||||
}
|
||||
|
||||
async function changeQuantity(lineId: string, current: number, delta: number) {
|
||||
const qty = current + delta;
|
||||
if (qty < 1 || pendingLines.has(lineId)) return;
|
||||
pendingLines = new Set(pendingLines).add(lineId);
|
||||
try {
|
||||
await basket.updateQuantity(lineId, qty);
|
||||
} catch (e) {
|
||||
errorMsg = e instanceof Error ? e.message : 'Failed to update quantity.';
|
||||
} finally {
|
||||
const next = new Set(pendingLines);
|
||||
next.delete(lineId);
|
||||
pendingLines = next;
|
||||
}
|
||||
}
|
||||
|
||||
async function removeLine(lineId: string) {
|
||||
if (pendingLines.has(lineId)) return;
|
||||
pendingLines = new Set(pendingLines).add(lineId);
|
||||
try {
|
||||
await basket.removeLine(lineId);
|
||||
} catch (e) {
|
||||
errorMsg = e instanceof Error ? e.message : 'Failed to remove item.';
|
||||
} finally {
|
||||
const next = new Set(pendingLines);
|
||||
next.delete(lineId);
|
||||
pendingLines = next;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<section class="mx-auto max-w-3xl px-6 py-16">
|
||||
{#if data.title}
|
||||
<h2 class="font-serif text-3xl font-bold md:text-4xl">{data.title}</h2>
|
||||
{/if}
|
||||
{#if data.heading}
|
||||
<p class="mt-2 text-fg-body/70">{data.heading}</p>
|
||||
{/if}
|
||||
|
||||
{#if basket.lines.length === 0}
|
||||
<div class="mt-12 rounded-2xl border border-charcoal/10 bg-white/60 px-6 py-16 text-center">
|
||||
<p class="font-serif text-xl">Your basket is empty</p>
|
||||
<p class="mt-2 text-sm text-fg-body/70">Pick a service or product above.</p>
|
||||
</div>
|
||||
{:else}
|
||||
<!-- Basket lines -->
|
||||
<ul class="mt-8 space-y-4">
|
||||
{#each basket.lines as line (line.id)}
|
||||
{@const pending = pendingLines.has(line.id)}
|
||||
<li class="flex items-center gap-4 rounded-2xl border border-charcoal/10 bg-white p-4 shadow-sm">
|
||||
{#if line.itemImageUrl}
|
||||
<img
|
||||
src={line.itemImageUrl}
|
||||
alt={line.itemName ?? 'Item'}
|
||||
class="h-16 w-16 shrink-0 rounded-xl object-cover"
|
||||
/>
|
||||
{:else}
|
||||
<div class="flex h-16 w-16 shrink-0 items-center justify-center rounded-xl bg-sage/15 font-serif text-xl text-sage-dark">
|
||||
{(line.itemName ?? '?').charAt(0).toUpperCase()}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="min-w-0 flex-1">
|
||||
<p class="truncate font-medium">{line.itemName ?? 'Item'}</p>
|
||||
{#if line.lineType === 'slot' && line.slotStart}
|
||||
<p class="text-sm text-fg-body/70">{formatSlotTime(line.slotStart)}</p>
|
||||
{/if}
|
||||
<p class="text-sm text-fg-body/70">{currency.format(line.itemPrice ?? 0)}</p>
|
||||
</div>
|
||||
|
||||
{#if line.lineType === 'item'}
|
||||
<div class="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="flex h-8 w-8 items-center justify-center rounded-full border border-charcoal/15 text-lg leading-none disabled:opacity-40"
|
||||
disabled={pending || line.quantity <= 1}
|
||||
aria-label="Decrease quantity"
|
||||
onclick={() => changeQuantity(line.id, line.quantity, -1)}
|
||||
>
|
||||
−
|
||||
</button>
|
||||
<span class="w-6 text-center">{line.quantity}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="flex h-8 w-8 items-center justify-center rounded-full border border-charcoal/15 text-lg leading-none disabled:opacity-40"
|
||||
disabled={pending}
|
||||
aria-label="Increase quantity"
|
||||
onclick={() => changeQuantity(line.id, line.quantity, 1)}
|
||||
>
|
||||
+
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<p class="w-20 shrink-0 text-right font-medium">
|
||||
{currency.format((line.itemPrice ?? 0) * line.quantity)}
|
||||
</p>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-charcoal/50 transition-colors hover:bg-terracotta/10 hover:text-terracotta disabled:opacity-40"
|
||||
disabled={pending}
|
||||
aria-label="Remove {line.itemName ?? 'item'}"
|
||||
onclick={() => removeLine(line.id)}
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
|
||||
<!-- Totals -->
|
||||
<div class="mt-6 rounded-2xl border border-charcoal/10 bg-white p-5">
|
||||
<div class="flex items-center justify-between">
|
||||
<span class="text-fg-body/70">Subtotal</span>
|
||||
<span class="font-serif text-xl font-bold">{currency.format(basket.total)}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-10 grid gap-10 md:grid-cols-2">
|
||||
<!-- Customer details -->
|
||||
<form
|
||||
class="space-y-4"
|
||||
novalidate
|
||||
onsubmit={(e) => {
|
||||
e.preventDefault();
|
||||
startPayment();
|
||||
}}
|
||||
>
|
||||
<h3 class="font-serif text-xl font-bold">Your details</h3>
|
||||
<div>
|
||||
<label class="mb-1 block text-sm font-medium" for="checkout-name">Name *</label>
|
||||
<input
|
||||
id="checkout-name"
|
||||
type="text"
|
||||
required
|
||||
class="w-full rounded-xl border border-charcoal/15 bg-white px-4 py-3 focus:ring-2 focus:ring-sage/50 focus:outline-none"
|
||||
bind:value={customer.name}
|
||||
autocomplete="name"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label class="mb-1 block text-sm font-medium" for="checkout-email">Email *</label>
|
||||
<input
|
||||
id="checkout-email"
|
||||
type="email"
|
||||
required
|
||||
class="w-full rounded-xl border border-charcoal/15 bg-white px-4 py-3 focus:ring-2 focus:ring-sage/50 focus:outline-none"
|
||||
bind:value={customer.email}
|
||||
autocomplete="email"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label class="mb-1 block text-sm font-medium" for="checkout-phone">Phone</label>
|
||||
<input
|
||||
id="checkout-phone"
|
||||
type="tel"
|
||||
class="w-full rounded-xl border border-charcoal/15 bg-white px-4 py-3 focus:ring-2 focus:ring-sage/50 focus:outline-none"
|
||||
bind:value={customer.phone}
|
||||
autocomplete="tel"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label class="mb-1 block text-sm font-medium" for="checkout-notes">
|
||||
{data.notesLabel || 'Notes or special requests'}
|
||||
</label>
|
||||
<textarea
|
||||
id="checkout-notes"
|
||||
rows="3"
|
||||
class="w-full rounded-xl border border-charcoal/15 bg-white px-4 py-3 focus:ring-2 focus:ring-sage/50 focus:outline-none"
|
||||
bind:value={customer.notes}
|
||||
></textarea>
|
||||
</div>
|
||||
|
||||
{#if payState === 'idle' || payState === 'creating'}
|
||||
<button
|
||||
type="submit"
|
||||
class="btn w-full rounded-full border-0 text-white"
|
||||
style="background-color: var(--color-primary, #8a9a7b);"
|
||||
disabled={payState === 'creating'}
|
||||
>
|
||||
{payLabel}
|
||||
</button>
|
||||
{/if}
|
||||
</form>
|
||||
|
||||
<!-- Payment -->
|
||||
<div>
|
||||
<h3 class="font-serif text-xl font-bold">Payment</h3>
|
||||
|
||||
{#if errorMsg}
|
||||
<div class="mt-4 flex items-start justify-between gap-3 rounded-xl border border-terracotta/40 bg-terracotta/10 px-4 py-3 text-sm text-charcoal" role="alert">
|
||||
<span>{errorMsg}</span>
|
||||
<button type="button" class="shrink-0 font-bold" aria-label="Dismiss" onclick={() => (errorMsg = '')}>✕</button>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if basketChanged}
|
||||
<p class="mt-4 rounded-xl border border-sage/30 bg-sage/10 px-4 py-3 text-sm">
|
||||
Basket changed — please press Pay again.
|
||||
</p>
|
||||
{/if}
|
||||
|
||||
<div
|
||||
bind:this={paymentDiv}
|
||||
class="mt-4 rounded-xl border border-charcoal/15 bg-white p-4 {payState === 'ready' || payState === 'confirming' ? '' : 'hidden'}"
|
||||
hidden={payState !== 'ready' && payState !== 'confirming'}
|
||||
></div>
|
||||
|
||||
{#if payState === 'ready' || payState === 'confirming'}
|
||||
<button
|
||||
type="button"
|
||||
class="btn mt-4 w-full rounded-full border-0 text-white"
|
||||
style="background-color: var(--color-primary, #8a9a7b);"
|
||||
disabled={payState === 'confirming'}
|
||||
onclick={confirmPayment}
|
||||
>
|
||||
{payState === 'confirming' ? 'Confirming…' : `Confirm payment — ${currency.format(basket.total)}`}
|
||||
</button>
|
||||
{/if}
|
||||
|
||||
{#if payState === 'idle' && !errorMsg}
|
||||
<p class="mt-4 text-sm text-fg-body/70">
|
||||
Fill in your details and press Pay to continue to secure payment.
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</section>
|
||||
30
app-public/src/lib/blocks/HeroBlock.svelte
Normal file
30
app-public/src/lib/blocks/HeroBlock.svelte
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
<script lang="ts">
|
||||
let { data } = $props<{
|
||||
data: {
|
||||
heading?: string;
|
||||
subheading?: string;
|
||||
buttonLabel?: string;
|
||||
buttonUrl?: string;
|
||||
};
|
||||
}>();
|
||||
</script>
|
||||
|
||||
<section class="relative flex min-h-[80vh] items-center justify-center overflow-hidden px-6 py-20 md:min-h-[90vh]">
|
||||
<div class="relative z-10 mx-auto max-w-4xl text-center">
|
||||
<h1 class="animate-fade-in text-5xl leading-tight text-fg-heading md:text-7xl lg:text-8xl" style="font-family: 'Playfair Display', Georgia, serif;">
|
||||
{data.heading || 'Holistic and Experiential Learning about Happiness'}
|
||||
</h1>
|
||||
{#if data.subheading}
|
||||
<p class="animate-fade-in mx-auto mt-6 max-w-2xl text-lg leading-relaxed text-fg-subheading/70 md:text-xl" style="animation-delay: 0.15s;">
|
||||
{data.subheading}
|
||||
</p>
|
||||
{/if}
|
||||
{#if data.buttonLabel}
|
||||
<div class="animate-fade-in mt-10" style="animation-delay: 0.3s;">
|
||||
<a class="btn rounded-full border-0 bg-sage px-10 py-3 text-lg text-white shadow-lg transition hover:bg-sage-dark hover:shadow-xl" href={data.buttonUrl || '/book'}>
|
||||
{data.buttonLabel}
|
||||
</a>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</section>
|
||||
22
app-public/src/lib/blocks/ImageTextBlock.svelte
Normal file
22
app-public/src/lib/blocks/ImageTextBlock.svelte
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
<script lang="ts">
|
||||
import { scrollReveal } from '$lib/scrollReveal';
|
||||
|
||||
let { data } = $props<{
|
||||
data: { url?: string; alt?: string; content?: string; imagePosition?: 'left' | 'right' };
|
||||
}>();
|
||||
</script>
|
||||
|
||||
<section use:scrollReveal class="reveal mx-auto max-w-6xl px-6 py-14 md:py-20">
|
||||
<div class="grid items-center gap-10 md:grid-cols-2">
|
||||
<div class:md:order-2={data.imagePosition === 'right'} class="overflow-hidden rounded-[2rem] bg-sage/10 shadow-sm">
|
||||
{#if data.url}
|
||||
<img class="aspect-[4/5] w-full object-cover" src={data.url} alt={data.alt || ''} />
|
||||
{:else}
|
||||
<div class="grid aspect-[4/5] place-items-center text-sage-dark">Upload an image</div>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="prose-wellness text-lg text-fg-body/80">
|
||||
{@html data.content || '<h2>A gentler rhythm</h2><p>Pair meaningful copy with a calming studio image.</p>'}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
313
app-public/src/lib/blocks/ShopBlock.svelte
Normal file
313
app-public/src/lib/blocks/ShopBlock.svelte
Normal file
|
|
@ -0,0 +1,313 @@
|
|||
<script lang="ts">
|
||||
import type { ShopBlockData, ItemRecord, SlotRecord } from '$lib/types';
|
||||
import { getBasketContext } from '$lib/basket.svelte';
|
||||
import { getCurrentAndNextMonths } from '$lib/calendar';
|
||||
|
||||
let { data = {}, items = [], slots = [] } = $props<{
|
||||
data: ShopBlockData;
|
||||
items?: ItemRecord[];
|
||||
slots?: SlotRecord[];
|
||||
}>();
|
||||
|
||||
const basket = getBasketContext();
|
||||
|
||||
// Per-card interaction state. Instances are created per component instance
|
||||
// (never shared at module level); keyed by item id so each card is independent.
|
||||
class CardState {
|
||||
pickerOpen = $state(false);
|
||||
selectedDayKey = $state<string | null>(null);
|
||||
adding = $state(false);
|
||||
errorMsg = $state<string | null>(null);
|
||||
justAdded = $state(false);
|
||||
pendingSlotId = $state<string | null>(null);
|
||||
}
|
||||
|
||||
let cardStates = $state<Record<string, CardState>>({});
|
||||
|
||||
const months = getCurrentAndNextMonths();
|
||||
const priceFormatter = new Intl.NumberFormat(undefined, { style: 'currency', currency: 'EUR' });
|
||||
const timeFormat: Intl.DateTimeFormatOptions = { hour: '2-digit', minute: '2-digit' };
|
||||
const weekdayLetters = ['S', 'M', 'T', 'W', 'T', 'F', 'S'];
|
||||
|
||||
let visibleItems: ItemRecord[] = $derived.by(() => {
|
||||
let result: ItemRecord[] = items;
|
||||
if (data.itemTypeFilter === 'item' || data.itemTypeFilter === 'item_with_time') {
|
||||
result = result.filter((i) => i.type === data.itemTypeFilter);
|
||||
}
|
||||
if (data.itemIds?.length) {
|
||||
const wanted = new Set(data.itemIds);
|
||||
result = result
|
||||
.filter((i) => wanted.has(i.id))
|
||||
.sort((a, b) => data.itemIds!.indexOf(a.id) - data.itemIds!.indexOf(b.id));
|
||||
}
|
||||
return result;
|
||||
});
|
||||
|
||||
// item id -> day key ('YYYY-MM-DD') -> slots on that day, sorted by start time
|
||||
let slotsByDay = $derived.by<Map<string, Map<string, SlotRecord[]>>>(() => {
|
||||
const map = new Map<string, Map<string, SlotRecord[]>>();
|
||||
for (const slot of slots) {
|
||||
const day = new Date(slot.start);
|
||||
if (Number.isNaN(day.getTime())) continue;
|
||||
const key = `${day.getFullYear()}-${`${day.getMonth() + 1}`.padStart(2, '0')}-${`${day.getDate()}`.padStart(2, '0')}`;
|
||||
let itemMap = map.get(slot.item);
|
||||
if (!itemMap) {
|
||||
itemMap = new Map();
|
||||
map.set(slot.item, itemMap);
|
||||
}
|
||||
const list = itemMap.get(key);
|
||||
if (list) list.push(slot);
|
||||
else itemMap.set(key, [slot]);
|
||||
}
|
||||
for (const itemMap of map.values()) {
|
||||
for (const list of itemMap.values()) {
|
||||
list.sort((a, b) => new Date(a.start).getTime() - new Date(b.start).getTime());
|
||||
}
|
||||
}
|
||||
return map;
|
||||
});
|
||||
|
||||
let isList = $derived(data.layout === 'list');
|
||||
|
||||
// Lazily create card state for whatever items are rendered.
|
||||
$effect(() => {
|
||||
for (const item of visibleItems) {
|
||||
if (!cardStates[item.id]) cardStates[item.id] = new CardState();
|
||||
}
|
||||
});
|
||||
|
||||
function togglePicker(itemId: string) {
|
||||
const state = cardStates[itemId];
|
||||
if (!state) return;
|
||||
state.pickerOpen = !state.pickerOpen;
|
||||
state.errorMsg = null;
|
||||
state.justAdded = false;
|
||||
state.selectedDayKey = null;
|
||||
}
|
||||
|
||||
function errorMessage(e: unknown, fallback: string) {
|
||||
return e instanceof Error && e.message ? e.message : fallback;
|
||||
}
|
||||
|
||||
async function addItem(itemId: string) {
|
||||
const state = cardStates[itemId];
|
||||
if (!state || state.adding) return;
|
||||
state.adding = true;
|
||||
state.errorMsg = null;
|
||||
try {
|
||||
await basket.addItemLine(itemId, 1);
|
||||
} catch (e) {
|
||||
state.errorMsg = errorMessage(e, 'Could not add this item to your basket.');
|
||||
} finally {
|
||||
state.adding = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function addSlot(itemId: string, slotId: string) {
|
||||
const state = cardStates[itemId];
|
||||
if (!state || state.adding) return;
|
||||
state.adding = true;
|
||||
state.pendingSlotId = slotId;
|
||||
state.errorMsg = null;
|
||||
try {
|
||||
await basket.addSlotLine(slotId);
|
||||
state.justAdded = true;
|
||||
} catch (e) {
|
||||
state.errorMsg = errorMessage(e, 'Could not book this time slot.');
|
||||
} finally {
|
||||
state.adding = false;
|
||||
state.pendingSlotId = null;
|
||||
}
|
||||
}
|
||||
|
||||
function formatTime(iso: string) {
|
||||
return new Date(iso).toLocaleTimeString(undefined, timeFormat);
|
||||
}
|
||||
</script>
|
||||
|
||||
<section class="mx-auto max-w-6xl px-6 py-16">
|
||||
{#if data.title}
|
||||
<h2 class="mb-12 text-center font-serif text-3xl text-charcoal md:text-4xl">{data.title}</h2>
|
||||
{/if}
|
||||
|
||||
<div class={isList ? 'flex flex-col gap-8' : 'grid gap-8 sm:grid-cols-2 lg:grid-cols-3'}>
|
||||
{#each visibleItems as item (item.id)}
|
||||
{@const ui = cardStates[item.id]}
|
||||
{@const itemSlotsByDay = slotsByDay.get(item.id)}
|
||||
{@const isService = item.type === 'item_with_time'}
|
||||
{@const soldOut = !isService && item.stock === 0}
|
||||
{@const itemInBasket = !isService && basket.lines.some((l) => l.item === item.id)}
|
||||
<article
|
||||
class={isList
|
||||
? 'rounded-2xl border border-charcoal/10 bg-white p-5 shadow-sm sm:flex sm:gap-6'
|
||||
: 'flex flex-col overflow-hidden rounded-2xl border border-charcoal/10 bg-white shadow-sm'}
|
||||
>
|
||||
{#if item.imageUrl}
|
||||
<img
|
||||
src={item.imageUrl}
|
||||
alt={item.name}
|
||||
class={isList ? 'h-44 w-full rounded-xl object-cover sm:h-auto sm:w-56 sm:shrink-0' : 'h-52 w-full object-cover'}
|
||||
/>
|
||||
{:else}
|
||||
<div
|
||||
class={isList
|
||||
? 'flex h-44 w-full items-center justify-center rounded-xl bg-sage/15 font-serif text-5xl text-sage-dark sm:h-auto sm:w-56 sm:shrink-0'
|
||||
: 'flex h-52 w-full items-center justify-center bg-sage/15 font-serif text-5xl text-sage-dark'}
|
||||
aria-hidden="true"
|
||||
>
|
||||
{item.name.trim().charAt(0).toUpperCase() || '·'}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class={isList ? 'mt-4 flex min-w-0 flex-1 flex-col sm:mt-0' : 'flex flex-1 flex-col p-5'}>
|
||||
<h3 class="font-serif text-xl text-charcoal">{item.name}</h3>
|
||||
{#if item.description}
|
||||
<p class="mt-1 line-clamp-3 text-sm text-charcoal/70">{item.description}</p>
|
||||
{/if}
|
||||
|
||||
<div class="mt-auto flex flex-wrap items-center gap-x-3 gap-y-1 pt-3">
|
||||
<span class="text-lg font-semibold text-sage-dark">{priceFormatter.format(item.price)}</span>
|
||||
{#if isService && item.duration != null}
|
||||
<span class="text-xs text-charcoal/60">{item.duration} min</span>
|
||||
{:else if !isService && item.stock != null && item.stock > 0 && item.stock <= 5}
|
||||
<span class="rounded-full bg-terracotta/15 px-2.5 py-0.5 text-xs font-medium text-terracotta">
|
||||
Only {item.stock} left
|
||||
</span>
|
||||
{:else if soldOut}
|
||||
<span class="rounded-full bg-terracotta/15 px-2.5 py-0.5 text-xs font-medium text-terracotta">
|
||||
Sold out
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if ui?.errorMsg}
|
||||
<div
|
||||
class="mt-3 flex items-start justify-between gap-2 rounded-lg border border-terracotta/30 bg-terracotta/10 px-3 py-2 text-sm text-charcoal"
|
||||
role="alert"
|
||||
>
|
||||
<span>{ui.errorMsg}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="shrink-0 leading-none text-charcoal/60 hover:text-charcoal"
|
||||
aria-label="Dismiss error"
|
||||
onclick={() => (ui.errorMsg = null)}
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="mt-4 flex items-center gap-3">
|
||||
{#if isService}
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center justify-center gap-2 rounded-full px-6 py-2.5 text-sm font-medium transition {ui?.pickerOpen
|
||||
? 'border border-charcoal/15 text-charcoal hover:bg-charcoal/5'
|
||||
: itemSlotsByDay?.size
|
||||
? 'bg-sage text-white hover:bg-sage-dark'
|
||||
: 'cursor-not-allowed bg-charcoal/10 text-charcoal/50'}"
|
||||
disabled={!itemSlotsByDay?.size && !ui?.pickerOpen}
|
||||
onclick={() => togglePicker(item.id)}
|
||||
>
|
||||
{itemSlotsByDay?.size ? (ui?.pickerOpen ? 'Close' : 'Book') : 'No availability'}
|
||||
</button>
|
||||
{:else}
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center justify-center gap-2 rounded-full bg-sage px-6 py-2.5 text-sm font-medium text-white transition hover:bg-sage-dark disabled:cursor-not-allowed disabled:bg-charcoal/10 disabled:text-charcoal/50"
|
||||
disabled={soldOut || ui?.adding}
|
||||
onclick={() => addItem(item.id)}
|
||||
>
|
||||
{#if ui?.adding}<span class="loading loading-spinner loading-xs"></span>{/if}
|
||||
{soldOut ? 'Sold out' : itemInBasket ? 'Add another' : 'Add to basket'}
|
||||
</button>
|
||||
{#if itemInBasket}
|
||||
<a
|
||||
href="/book"
|
||||
class="inline-flex items-center gap-1 text-sm font-medium text-sage-dark underline-offset-2 hover:underline"
|
||||
>✓ In basket</a
|
||||
>
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if isService && ui?.pickerOpen && itemSlotsByDay}
|
||||
<div class={isList ? 'mt-5 border-t border-charcoal/10 pt-5 sm:basis-full' : 'border-t border-charcoal/10 bg-warm p-4'}>
|
||||
<p class="mb-3 text-sm font-medium text-charcoal/70">Select a date</p>
|
||||
<div class="grid gap-6 sm:grid-cols-2">
|
||||
{#each months as month (month.label)}
|
||||
<div>
|
||||
<p class="mb-2 text-center text-sm font-medium text-charcoal/70">{month.label}</p>
|
||||
<div class="grid grid-cols-7 gap-1 text-center">
|
||||
{#each weekdayLetters as letter, i (i)}
|
||||
<span class="py-1 text-xs text-charcoal/40">{letter}</span>
|
||||
{/each}
|
||||
{#each month.days as day (day.dateKey)}
|
||||
{@const selectable = day.inMonth && itemSlotsByDay.has(day.dateKey)}
|
||||
{@const selected = selectable && ui.selectedDayKey === day.dateKey}
|
||||
<button
|
||||
type="button"
|
||||
disabled={!selectable}
|
||||
aria-pressed={selected}
|
||||
onclick={() => (ui.selectedDayKey = day.dateKey)}
|
||||
class="aspect-square rounded-full text-sm transition {selected
|
||||
? 'bg-sage font-semibold text-white'
|
||||
: selectable
|
||||
? 'cursor-pointer bg-sage/15 font-medium text-charcoal hover:bg-sage/35'
|
||||
: 'cursor-default text-charcoal/25'} {!day.inMonth ? 'opacity-40' : ''} {day.isToday &&
|
||||
!selected
|
||||
? 'ring-1 ring-sage/60'
|
||||
: ''}"
|
||||
>
|
||||
{day.dayNumber}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
{#if ui.selectedDayKey}
|
||||
{@const daySlots = itemSlotsByDay.get(ui.selectedDayKey) ?? []}
|
||||
<p class="mt-4 mb-2 text-sm font-medium text-charcoal/70">Available times</p>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
{#each daySlots as slot (slot.id)}
|
||||
{@const slotInBasket = basket.lines.some((l) => l.slot === slot.id)}
|
||||
<button
|
||||
type="button"
|
||||
disabled={slotInBasket || ui.adding}
|
||||
onclick={() => addSlot(item.id, slot.id)}
|
||||
class="inline-flex items-center gap-1.5 rounded-full border px-3.5 py-1.5 text-sm transition {slotInBasket
|
||||
? 'cursor-not-allowed border-transparent bg-sage/15 text-sage-dark'
|
||||
: 'border-charcoal/15 bg-white text-charcoal hover:border-sage hover:bg-sage/10'} disabled:opacity-60 {ui.adding &&
|
||||
!slotInBasket
|
||||
? 'cursor-wait'
|
||||
: ''}"
|
||||
>
|
||||
{#if ui.pendingSlotId === slot.id}
|
||||
<span class="loading loading-spinner loading-xs"></span>
|
||||
{/if}
|
||||
{formatTime(slot.start)}{item.duration != null ? ` · ${item.duration} min` : ''}{slotInBasket
|
||||
? ' · In basket'
|
||||
: ''}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
{:else}
|
||||
<p class="mt-4 text-sm text-charcoal/60">
|
||||
Days with availability are highlighted{item.duration != null ? ` · ${item.duration} min per session` : ''}.
|
||||
</p>
|
||||
{/if}
|
||||
|
||||
{#if ui.justAdded}
|
||||
<p class="mt-3 text-sm font-medium text-sage-dark">
|
||||
Added ✓ — <a href="/book" class="underline underline-offset-2 hover:no-underline">view basket</a>
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</article>
|
||||
{/each}
|
||||
</div>
|
||||
</section>
|
||||
7
app-public/src/lib/blocks/SpacerBlock.svelte
Normal file
7
app-public/src/lib/blocks/SpacerBlock.svelte
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
<script lang="ts">
|
||||
let { data } = $props<{ data: Record<string, any> }>();
|
||||
|
||||
const height = $derived(data.height ?? 64);
|
||||
</script>
|
||||
|
||||
<div style="height: {height}px;" class="w-full"></div>
|
||||
87
app-public/src/lib/blocks/TestimonialsBlock.svelte
Normal file
87
app-public/src/lib/blocks/TestimonialsBlock.svelte
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
<script lang="ts">
|
||||
let { data } = $props<{ data: Record<string, any> }>();
|
||||
|
||||
const testimonials = data.items || [
|
||||
{ text: 'Recently I started to experience incredible whole-body orgasms. And now I know how it works. My awareness around sexuality changed for good and I feel like a boss of my own life. What a joy to have this freedom of choice.', title: 'Anne' },
|
||||
{ text: 'I never thought it was possible to sense so much pleasure in my body without intense stimulations I got used to. After the series of sessions, I could feel something like a trance state by receiving only a gentle touch. That was a totally new experience for me.', title: 'Espen' },
|
||||
{ text: "Eva's sexual healing methods should be accessible to everyone. I am amazed by the depth and integrity of the message she conveys through her work. I was meeting Eva for healing my body and, as a result, I reconnected with my heart and soul too.", title: 'Marie' },
|
||||
{ text: "It is hard to surprise me with any sexual activity since I had many exciting experiments in my life. But I always suspected that there might be something more I have not yet felt and tried. Thanks to Eva I realised how much power I've got. Under her guidance, I have learnt to maximise my orgasmic potential and consciously play with arousal. By the way, my wife is also happy that I became enthusiastic about new sexual practices.", title: 'Jan' }
|
||||
];
|
||||
|
||||
const title = data.title || 'What They Say About Me';
|
||||
|
||||
// Simple state for carousel
|
||||
let currentIndex = $state(0);
|
||||
const totalSlides = testimonials.length;
|
||||
|
||||
function next() {
|
||||
currentIndex = (currentIndex + 1) % totalSlides;
|
||||
}
|
||||
|
||||
function prev() {
|
||||
currentIndex = (currentIndex - 1 + totalSlides) % totalSlides;
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="relative min-h-[400px]">
|
||||
<div class="flex flex-col items-center px-4 py-12 min-h-[400px]">
|
||||
<!-- Title -->
|
||||
<h2 class="text-fg-heading text-2xl md:text-3xl font-light tracking-wide">
|
||||
{title}
|
||||
</h2>
|
||||
|
||||
<!-- Testimonial carousel - fills remaining space and centers content vertically -->
|
||||
<div class="w-full max-w-3xl flex-1 flex items-center justify-center">
|
||||
<!-- Slides are stacked in a grid so the carousel keeps the height of the tallest testimonial. -->
|
||||
<div class="grid px-8 text-center w-full pt-4 md:pt-8">
|
||||
{#each testimonials as testimonial, i}
|
||||
<div class="col-start-1 row-start-1 transition-opacity duration-300 {i === currentIndex ? 'opacity-100' : 'pointer-events-none opacity-0'}" aria-hidden={i !== currentIndex}>
|
||||
<p class="text-fg-body/85 text-lg md:text-xl font-light leading-relaxed mb-8">
|
||||
"{testimonial.text}"
|
||||
</p>
|
||||
<p class="text-fg-subheading font-medium tracking-wider">
|
||||
— {testimonial.title}
|
||||
</p>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Navigation arrows -->
|
||||
<div class="flex justify-center items-center gap-8">
|
||||
<button
|
||||
type="button"
|
||||
onclick={prev}
|
||||
class="w-10 h-10 rounded-full flex items-center justify-center transition-colors hover:bg-[rgba(255,236,224,1)] hover:text-[#93384a] bg-[rgba(255,219,197,0.8)]"
|
||||
aria-label="Previous slide"
|
||||
>
|
||||
<svg viewBox="0 0 7.3 13" class="w-2 h-3" fill="none" stroke="currentColor" stroke-width="1.5">
|
||||
<polyline points="6.5,0.5 1.5,6.5 6.5,12.5" stroke-linecap="butt" stroke-linejoin="miter"/>
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
<!-- Dots/bullets -->
|
||||
<div class="flex text-fg-heading gap-3">
|
||||
{#each testimonials as _, i}
|
||||
<button
|
||||
type="button"
|
||||
class="w-2.5 h-2.5 rounded-full border-2 transition-colors {i === currentIndex ? 'bg-current' : 'border-current'}"
|
||||
aria-label="Go to slide {i + 1}"
|
||||
onclick={() => (currentIndex = i)}
|
||||
></button>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onclick={next}
|
||||
class="w-10 h-10 rounded-full flex items-center justify-center transition-colors hover:bg-[rgba(255,236,224,1)] hover:text-[#93384a] bg-[rgba(255,219,197,0.8)]"
|
||||
aria-label="Next slide"
|
||||
>
|
||||
<svg viewBox="0 0 7.3 13" class="w-2 h-3" fill="none" stroke="currentColor" stroke-width="1.5">
|
||||
<polyline points="0.5,0.5 5.5,6.5 0.5,12.5" stroke-linecap="butt" stroke-linejoin="miter"/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
11
app-public/src/lib/blocks/TextBlock.svelte
Normal file
11
app-public/src/lib/blocks/TextBlock.svelte
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
<script lang="ts">
|
||||
import { scrollReveal } from '$lib/scrollReveal';
|
||||
|
||||
let { data } = $props<{ data: { content?: string } }>();
|
||||
</script>
|
||||
|
||||
<section use:scrollReveal class="reveal mx-auto max-w-3xl px-6 py-12 md:py-16">
|
||||
<div class="prose-wellness text-lg text-fg-body/85">
|
||||
{@html data.content || '<h2>Welcome</h2><p>Add warm, inviting copy in the CMS.</p>'}
|
||||
</div>
|
||||
</section>
|
||||
31
app-public/src/lib/blocks/TimelineBlock.svelte
Normal file
31
app-public/src/lib/blocks/TimelineBlock.svelte
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
<script lang="ts">
|
||||
import { scrollReveal } from '$lib/scrollReveal';
|
||||
|
||||
type TimelineItem = { title: string; description: string };
|
||||
let { data } = $props<{ data: { items?: TimelineItem[] } }>();
|
||||
let items = $derived(data.items?.length ? data.items : [
|
||||
{ title: 'Your story here', description: 'Add milestones, training, or the journey behind the practice.' }
|
||||
]);
|
||||
let widths = $derived(items.map((_: TimelineItem, i: number) => {
|
||||
const opts = ['w-[78%]', 'w-[85%]', 'w-[90%]', 'w-[95%]', 'w-[98%]'];
|
||||
return opts[(i * 7 + 3) % opts.length];
|
||||
}));
|
||||
</script>
|
||||
|
||||
<section class="mx-auto max-w-7xl px-6 py-12">
|
||||
<div class="mb-8 text-center">
|
||||
<p class="mb-2 text-xs font-semibold uppercase tracking-[0.25em] text-sage-dark">Journey</p>
|
||||
<h2 class="text-3xl md:text-4xl" use:scrollReveal>A practice shaped over time</h2>
|
||||
</div>
|
||||
<div class="relative md:before:absolute md:before:left-1/2 md:before:top-0 md:before:h-full md:before:w-px md:before:bg-sage/30">
|
||||
{#each items as item, index}
|
||||
<div use:scrollReveal class="reveal relative mb-[-1rem] grid gap-4 md:grid-cols-2 md:gap-8">
|
||||
<div class="hidden md:block" class:md:order-2={index % 2 === 0}></div>
|
||||
<article class="rounded-2xl bg-white/75 p-5 shadow-sm ring-1 ring-charcoal/5 -mt-4 {widths[index]} {index % 2 === 0 ? 'md:ml-auto md:text-right' : ''}">
|
||||
<h3 class="text-xl">{item.title}</h3>
|
||||
<p class="mt-2 text-sm leading-6 text-fg-body/70">{item.description}</p>
|
||||
</article>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</section>
|
||||
125
app-public/src/lib/blocks/UpcomingCalendarBlock.svelte
Normal file
125
app-public/src/lib/blocks/UpcomingCalendarBlock.svelte
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
<script lang="ts">
|
||||
import type { CalendarEventRecord, UpcomingCalendarBlockData } from '$lib/types';
|
||||
import {
|
||||
dateKey,
|
||||
eventMatchesCategories,
|
||||
eventOverlapsDay,
|
||||
eventRange,
|
||||
formatEventDateRange,
|
||||
getCurrentAndNextMonths,
|
||||
isExternalLink,
|
||||
normalizeLink,
|
||||
sortEvents
|
||||
} from '$lib/calendar';
|
||||
|
||||
let { data = {}, events = [] } = $props<{
|
||||
data: UpcomingCalendarBlockData;
|
||||
events?: CalendarEventRecord[];
|
||||
}>();
|
||||
|
||||
const weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
|
||||
let months = $derived(getCurrentAndNextMonths());
|
||||
let selectedCategories = $derived(data.categories || []);
|
||||
let visibleEvents = $derived(sortEvents(events.filter((event: CalendarEventRecord) => event.published && eventMatchesCategories(event, selectedCategories))));
|
||||
|
||||
function eventsForDay(date: Date) {
|
||||
return visibleEvents.filter((event) => eventOverlapsDay(event, date));
|
||||
}
|
||||
|
||||
function eventStyle(event: CalendarEventRecord) {
|
||||
return `--event-color: ${event.color || '#8a9a7b'};`;
|
||||
}
|
||||
|
||||
function segmentMeta(event: CalendarEventRecord, date: Date) {
|
||||
const { start, end } = eventRange(event);
|
||||
const isStart = dateKey(start) === dateKey(date);
|
||||
const isEnd = dateKey(end) === dateKey(date);
|
||||
const startsWeek = date.getDay() === 0;
|
||||
const endsWeek = date.getDay() === 6;
|
||||
const visualStart = isStart || startsWeek;
|
||||
const visualEnd = isEnd || endsWeek;
|
||||
|
||||
return {
|
||||
showLabel: visualStart,
|
||||
classes: [
|
||||
visualStart ? 'rounded-l-xl' : 'rounded-l-none -ml-3',
|
||||
visualEnd ? 'rounded-r-xl' : 'rounded-r-none -mr-3',
|
||||
visualStart && visualEnd ? 'mx-0' : '',
|
||||
!visualStart && !visualEnd ? '-mx-3' : ''
|
||||
].filter(Boolean).join(' ')
|
||||
};
|
||||
}
|
||||
</script>
|
||||
|
||||
<section class="mx-auto max-w-7xl px-6 py-16">
|
||||
<div class="mb-10 text-center">
|
||||
<h2 class="font-display mt-2 text-4xl text-charcoal md:text-5xl">{data.title}</h2>
|
||||
</div>
|
||||
|
||||
{#if visibleEvents.length === 0}
|
||||
<div class="mx-auto max-w-2xl rounded-[2rem] border border-sage/20 bg-white/70 p-8 text-center shadow-sm">
|
||||
<p class="text-charcoal/70">No upcoming events are available for the selected categories.</p>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="isolate grid gap-8 lg:grid-cols-2">
|
||||
{#each months as month}
|
||||
<div class="relative z-0 overflow-visible rounded-[2rem] border border-sage/15 bg-white/80 p-5 shadow-sm backdrop-blur hover:z-[9000] focus-within:z-[9000]">
|
||||
<h3 class="font-display mb-5 text-center text-3xl text-charcoal">{month.label}</h3>
|
||||
<div class="mb-2 grid grid-cols-7 gap-1 text-center text-xs font-semibold uppercase tracking-wide text-charcoal/45">
|
||||
{#each weekdays as weekday}<div>{weekday}</div>{/each}
|
||||
</div>
|
||||
<div class="grid grid-cols-7 gap-1 overflow-visible">
|
||||
{#each month.days as day}
|
||||
<div class="relative min-h-28 overflow-visible rounded-2xl border p-2 {day.inMonth ? 'border-sage/10 bg-warm/60' : 'border-sage/5 bg-warm/25'}" class:ring-2={day.isToday} class:ring-sage={day.isToday}>
|
||||
<div class="mb-1 flex items-center justify-between">
|
||||
<span class="text-sm font-semibold {day.inMonth ? 'text-charcoal/70' : 'text-charcoal/30'}">{day.dayNumber}</span>
|
||||
</div>
|
||||
<div class="space-y-1">
|
||||
{#each eventsForDay(day.date) as event}
|
||||
{@const href = normalizeLink(event.link)}
|
||||
{@const label = `${event.name}${event.description ? `: ${event.description}` : ''}`}
|
||||
{@const segment = segmentMeta(event, day.date)}
|
||||
{#if href}
|
||||
<a
|
||||
class="group/event relative z-10 block px-2 py-1 text-left text-[0.7rem] font-semibold leading-tight text-white shadow-sm hover:z-[9999] hover:shadow-md focus:z-[9999] focus:outline-none focus:ring-2 focus:ring-charcoal/30 {segment.classes}"
|
||||
href={href}
|
||||
target={isExternalLink(href) ? '_blank' : undefined}
|
||||
rel={isExternalLink(href) ? 'noreferrer' : undefined}
|
||||
style={eventStyle(event)}
|
||||
aria-label={label}
|
||||
>
|
||||
<span class="absolute inset-0 bg-[var(--event-color)] {segment.classes}"></span>
|
||||
<span class="relative block truncate">{segment.showLabel ? event.name : '\u00a0'}</span>
|
||||
<span class="pointer-events-none absolute bottom-full left-0 z-[10000] mb-2 hidden w-64 rounded-xl bg-charcoal p-3 text-xs font-normal leading-relaxed text-white shadow-xl group-hover/event:block group-focus/event:block">
|
||||
<strong class="block">{event.name}</strong>
|
||||
<span class="block opacity-80">{formatEventDateRange(event)}</span>
|
||||
{#if event.description}<span class="mt-1 block">{event.description}</span>{/if}
|
||||
</span>
|
||||
</a>
|
||||
{:else}
|
||||
<span
|
||||
class="group/event relative z-10 block px-2 py-1 text-left text-[0.7rem] font-semibold leading-tight text-white shadow-sm hover:z-[9999] focus:z-[9999] focus:outline-none focus:ring-2 focus:ring-charcoal/30 {segment.classes}"
|
||||
style={eventStyle(event)}
|
||||
tabindex="0"
|
||||
role="button"
|
||||
aria-label={label}
|
||||
>
|
||||
<span class="absolute inset-0 bg-[var(--event-color)] {segment.classes}"></span>
|
||||
<span class="relative block truncate">{segment.showLabel ? event.name : '\u00a0'}</span>
|
||||
<span class="pointer-events-none absolute bottom-full left-0 z-[10000] mb-2 hidden w-64 rounded-xl bg-charcoal p-3 text-xs font-normal leading-relaxed text-white shadow-xl group-hover/event:block group-focus/event:block">
|
||||
<strong class="block">{event.name}</strong>
|
||||
<span class="block opacity-80">{formatEventDateRange(event)}</span>
|
||||
{#if event.description}<span class="mt-1 block">{event.description}</span>{/if}
|
||||
</span>
|
||||
</span>
|
||||
{/if}
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</section>
|
||||
1
app-public/src/lib/calendar.ts
Normal file
1
app-public/src/lib/calendar.ts
Normal file
|
|
@ -0,0 +1 @@
|
|||
export * from '$shared/calendar';
|
||||
30
app-public/src/lib/scrollReveal.ts
Normal file
30
app-public/src/lib/scrollReveal.ts
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
/**
|
||||
* Scroll reveal Svelte action — applies a CSS class when the element enters the viewport.
|
||||
* Usage: <div use:scrollReveal class="reveal">...</div>
|
||||
* The `reveal` class is hidden initially; `reveal-visible` is added on intersection.
|
||||
*/
|
||||
|
||||
export function scrollReveal(node: HTMLElement, delay: number = 0) {
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
for (const entry of entries) {
|
||||
if (entry.isIntersecting) {
|
||||
if (delay > 0) {
|
||||
node.style.transitionDelay = `${delay}s`;
|
||||
}
|
||||
node.classList.add('reveal-visible');
|
||||
observer.unobserve(node);
|
||||
}
|
||||
}
|
||||
},
|
||||
{ threshold: 0.1, rootMargin: '0px 0px -40px 0px' }
|
||||
);
|
||||
|
||||
observer.observe(node);
|
||||
|
||||
return {
|
||||
destroy() {
|
||||
observer.disconnect();
|
||||
}
|
||||
};
|
||||
}
|
||||
187
app-public/src/lib/server/basket.ts
Normal file
187
app-public/src/lib/server/basket.ts
Normal file
|
|
@ -0,0 +1,187 @@
|
|||
import type PocketBase from 'pocketbase';
|
||||
import type { Basket, BasketLine } from '$lib/types';
|
||||
import { getFileUrl } from '$lib/pb';
|
||||
|
||||
export const BASKET_COOKIE = 'basket_id';
|
||||
/** Basket lifetime — refreshed on every basket API call. */
|
||||
export const BASKET_TTL_MS = 24 * 60 * 60 * 1000; // 24h
|
||||
/** How long a slot stays held once added to a basket / after a failed payment. */
|
||||
export const SLOT_HOLD_MS = 10 * 60 * 1000; // 10 min
|
||||
/** Hold extended to this once a payment is in progress, so the slot survives
|
||||
* the customer entering card details / retrying a declined card. */
|
||||
export const SLOT_CHECKOUT_HOLD_MS = 30 * 60 * 1000; // 30 min
|
||||
|
||||
function now() {
|
||||
return new Date();
|
||||
}
|
||||
|
||||
function iso(date: Date) {
|
||||
return date.toISOString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Release any slots whose hold has expired, removing their basket lines
|
||||
* and flipping them back to `available`. Also marks expired active
|
||||
* baskets as `abandoned`. Runs lazily on basket reads / checkout.
|
||||
*
|
||||
* The expiry check is done in JS (parsing `heldUntil` as a UTC date) rather
|
||||
* than via a PocketBase date-string filter, so a slot is never released
|
||||
* *before* its hold genuinely lapses — regardless of how PocketBase stores /
|
||||
* compares the date field. A slot is held for the full SLOT_HOLD_MS (or
|
||||
* SLOT_CHECKOUT_HOLD_MS during payment).
|
||||
*/
|
||||
export async function sweepExpiredHolds(pb: PocketBase) {
|
||||
const nowMs = Date.now();
|
||||
|
||||
// 1. Release expired slot holds (and drop the lines holding them)
|
||||
const heldSlots = await pb
|
||||
.collection('slots')
|
||||
.getFullList({ filter: `status = 'held'` })
|
||||
.catch(() => []);
|
||||
for (const slot of heldSlots) {
|
||||
const heldUntilMs = slot.heldUntil ? Date.parse(slot.heldUntil) : NaN;
|
||||
// Still valid, or no parseable hold to judge by — leave it alone.
|
||||
if (Number.isNaN(heldUntilMs) || heldUntilMs > nowMs) continue;
|
||||
|
||||
const lines = await pb
|
||||
.collection('basket_lines')
|
||||
.getFullList({ filter: `slot = "${slot.id}"` })
|
||||
.catch(() => []);
|
||||
for (const line of lines) {
|
||||
await pb.collection('basket_lines').delete(line.id).catch(() => {});
|
||||
}
|
||||
await pb
|
||||
.collection('slots')
|
||||
.update(slot.id, { status: 'available', heldUntil: null })
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
// 2. Abandon expired active baskets (their slot holds were already
|
||||
// covered by heldUntil above — same 10-min window < 24h basket TTL)
|
||||
const nowIso = iso(now());
|
||||
await pb
|
||||
.collection('baskets')
|
||||
.getFullList({ filter: `status = 'active' && expiresAt < "${nowIso}"` })
|
||||
.then(async (expired) => {
|
||||
for (const basket of expired) {
|
||||
await pb.collection('baskets').update(basket.id, { status: 'abandoned' }).catch(() => {});
|
||||
}
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
/** Map raw PB records (with expand) to our Basket type. */
|
||||
function mapBasket(record: Record<string, any>, lines: Record<string, any>[]): Basket {
|
||||
const mappedLines: BasketLine[] = lines.map((line) => {
|
||||
const item = line.expand?.item;
|
||||
const slot = line.expand?.slot;
|
||||
const media = item?.expand?.image;
|
||||
return {
|
||||
id: line.id,
|
||||
basket: line.basket,
|
||||
item: line.item,
|
||||
slot: line.slot || null,
|
||||
quantity: line.quantity,
|
||||
lineType: line.lineType,
|
||||
itemName: item?.name,
|
||||
itemPrice: item?.price,
|
||||
itemImageUrl: media ? getFileUrl('media', media.id, media.file) : undefined,
|
||||
slotStart: slot?.start,
|
||||
slotEnd: slot?.end
|
||||
};
|
||||
});
|
||||
return {
|
||||
id: record.id,
|
||||
status: record.status,
|
||||
expiresAt: record.expiresAt,
|
||||
email: record.email || null,
|
||||
customerDetails: record.customerDetails || null,
|
||||
stripePaymentIntentId: record.stripePaymentIntentId || null,
|
||||
lines: mappedLines
|
||||
};
|
||||
}
|
||||
|
||||
/** Load a basket + its lines (with item/slot expand) by basket id. */
|
||||
export async function loadBasket(pb: PocketBase, basketId: string): Promise<Basket | null> {
|
||||
try {
|
||||
const record = await pb.collection('baskets').getOne(basketId);
|
||||
if (record.status !== 'active') return null;
|
||||
const lines = await pb
|
||||
.collection('basket_lines')
|
||||
.getFullList({ filter: `basket = "${basketId}"`, expand: 'item,slot,item.image' });
|
||||
return mapBasket(record, lines);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Create a fresh active basket. */
|
||||
export async function createBasket(pb: PocketBase): Promise<Basket> {
|
||||
const record = await pb.collection('baskets').create({
|
||||
status: 'active',
|
||||
expiresAt: iso(new Date(Date.now() + BASKET_TTL_MS))
|
||||
});
|
||||
return {
|
||||
id: record.id,
|
||||
status: 'active',
|
||||
expiresAt: record.expiresAt,
|
||||
email: null,
|
||||
customerDetails: null,
|
||||
stripePaymentIntentId: null,
|
||||
lines: []
|
||||
};
|
||||
}
|
||||
|
||||
/** Touch the basket expiry (rolling TTL). */
|
||||
export async function touchBasket(pb: PocketBase, basketId: string) {
|
||||
await pb
|
||||
.collection('baskets')
|
||||
.update(basketId, { expiresAt: iso(new Date(Date.now() + BASKET_TTL_MS)) })
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
/** Release a slot hold for a basket line (slot back to available). */
|
||||
export async function releaseLineHold(pb: PocketBase, line: { slot?: string | null }) {
|
||||
if (!line.slot) return;
|
||||
await pb
|
||||
.collection('slots')
|
||||
.update(line.slot, { status: 'available', heldUntil: null })
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-reserve (extend) the hold on every slot line in a basket, as long as
|
||||
* the slot is still in `held` status. Used:
|
||||
* - at checkout start (create-intent) with SLOT_CHECKOUT_HOLD_MS, so a
|
||||
* service survives the customer entering card details / retrying a
|
||||
* declined card;
|
||||
* - after a failed payment (webhook) with SLOT_HOLD_MS, so the customer
|
||||
* can retry within a fresh 10-minute window.
|
||||
* The slot is genuinely still the customer's (nobody else could grab it
|
||||
* while `held`), so renewing is safe. Slots whose status is no longer
|
||||
* `held` (e.g. released and re-booked by someone else) are returned so the
|
||||
* caller can inform the user.
|
||||
*/
|
||||
export async function extendBasketHolds(
|
||||
pb: PocketBase,
|
||||
basketId: string,
|
||||
durationMs = SLOT_HOLD_MS
|
||||
): Promise<string[]> {
|
||||
const unheld: string[] = [];
|
||||
const lines = await pb
|
||||
.collection('basket_lines')
|
||||
.getFullList({ filter: `basket = "${basketId}" && lineType = "slot"` })
|
||||
.catch(() => []);
|
||||
const until = iso(new Date(Date.now() + durationMs));
|
||||
for (const line of lines) {
|
||||
const slotId = line.slot;
|
||||
if (!slotId) continue;
|
||||
const slot = await pb.collection('slots').getOne(slotId).catch(() => null);
|
||||
if (slot && slot.status === 'held') {
|
||||
await pb.collection('slots').update(slotId, { heldUntil: until }).catch(() => {});
|
||||
} else {
|
||||
unheld.push(line.id);
|
||||
}
|
||||
}
|
||||
return unheld;
|
||||
}
|
||||
53
app-public/src/lib/server/pb-admin.ts
Normal file
53
app-public/src/lib/server/pb-admin.ts
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
import PocketBase, { ClientResponseError } from 'pocketbase';
|
||||
import { env } from '$env/dynamic/private';
|
||||
|
||||
let adminPb: PocketBase | null = null;
|
||||
let authPromise: Promise<PocketBase> | null = null;
|
||||
|
||||
async function authenticate(): Promise<PocketBase> {
|
||||
const url = env.POCKETBASE_INTERNAL_URL;
|
||||
const pb = new PocketBase(url);
|
||||
pb.autoCancellation(false);
|
||||
|
||||
const email = env.POCKETBASE_ADMIN_EMAIL;
|
||||
const password = env.POCKETBASE_ADMIN_PASSWORD;
|
||||
if (!email || !password) throw new Error('POCKETBASE_ADMIN_EMAIL and POCKETBASE_ADMIN_PASSWORD must be set');
|
||||
|
||||
await pb.collection('_superusers').authWithPassword(email, password);
|
||||
adminPb = pb;
|
||||
return pb;
|
||||
}
|
||||
|
||||
/**
|
||||
* Server-only PocketBase client authenticated as admin.
|
||||
* Used by basket/checkout/webhook API routes that need to bypass
|
||||
* collection-level API rules (create baskets, hold slots, create orders).
|
||||
*
|
||||
* Concurrent callers share one in-flight auth attempt; if the cached token
|
||||
* has since been invalidated (401 on first use), we re-authenticate once.
|
||||
*/
|
||||
export async function getAdminPb(): Promise<PocketBase> {
|
||||
if (adminPb?.authStore.isValid) return adminPb;
|
||||
authPromise ??= authenticate().finally(() => {
|
||||
authPromise = null;
|
||||
});
|
||||
return authPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run `fn` with the admin client; on a 401 (stale/invalidated token),
|
||||
* re-authenticate and retry exactly once.
|
||||
*/
|
||||
export async function withAdminPb<T>(fn: (pb: PocketBase) => Promise<T>): Promise<T> {
|
||||
const pb = await getAdminPb();
|
||||
try {
|
||||
return await fn(pb);
|
||||
} catch (e) {
|
||||
if (e instanceof ClientResponseError && e.status === 401) {
|
||||
pb.authStore.clear();
|
||||
adminPb = null;
|
||||
return fn(await getAdminPb());
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
15
app-public/src/lib/stripe-client.ts
Normal file
15
app-public/src/lib/stripe-client.ts
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
import { loadStripe as _loadStripe } from '@stripe/stripe-js';
|
||||
import { env } from '$env/dynamic/public';
|
||||
import { browser } from '$app/environment';
|
||||
|
||||
let stripePromise: ReturnType<typeof _loadStripe> | null = null;
|
||||
|
||||
export function loadStripe() {
|
||||
if (!browser) return null;
|
||||
if (!stripePromise) {
|
||||
const key = env.PUBLIC_STRIPE_PUBLISHABLE_KEY;
|
||||
if (!key) throw new Error('PUBLIC_STRIPE_PUBLISHABLE_KEY is not set');
|
||||
stripePromise = _loadStripe(key);
|
||||
}
|
||||
return stripePromise;
|
||||
}
|
||||
1
app-public/src/lib/types.ts
Normal file
1
app-public/src/lib/types.ts
Normal file
|
|
@ -0,0 +1 @@
|
|||
export * from '$shared/types';
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue