From 246b1990ca263b0ba57c31d97e8fb518b9abe956 Mon Sep 17 00:00:00 2001 From: Jakub Dorfman Date: Fri, 5 Jun 2026 15:32:23 +0200 Subject: [PATCH] added reverse proxy --- .dockerignore | 12 +- .env.example | 4 +- AGENTS.md | 211 +++--- CONTRACT.md | 414 +++++------ Caddyfile | 17 + Dockerfile | 46 +- README.md | 227 +++--- app/.env.example | 2 +- app/src/app.css | 280 +++---- app/src/hooks.server.ts | 56 +- app/src/lib/admin/BlockList.svelte | 126 ++-- app/src/lib/admin/blockDefaults.ts | 138 ++-- app/src/lib/admin/editors/BlockEditor.svelte | 588 +++++++-------- .../lib/admin/editors/ImageUploader.svelte | 210 +++--- .../lib/admin/editors/RichTextEditor.svelte | 156 ++-- .../lib/admin/editors/SegmentedControl.svelte | 74 +- app/src/lib/blocks/BackgroundWrapper.svelte | 108 +-- app/src/lib/blocks/BlockRenderer.svelte | 88 +-- app/src/lib/blocks/ButtonBlock.svelte | 52 +- app/src/lib/blocks/HeroBlock.svelte | 60 +- app/src/lib/blocks/ImageTextBlock.svelte | 44 +- app/src/lib/blocks/SpacerBlock.svelte | 12 +- app/src/lib/blocks/TestimonialsBlock.svelte | 172 ++--- app/src/lib/blocks/TextBlock.svelte | 22 +- app/src/lib/blocks/TimelineBlock.svelte | 62 +- .../lib/blocks/UpcomingCalendarBlock.svelte | 252 +++---- app/src/lib/calendar.ts | 398 +++++----- app/src/lib/components/Footer.svelte | 52 +- app/src/lib/components/Header.svelte | 54 +- app/src/lib/exportImport.ts | 276 +++---- app/src/lib/pb.ts | 74 +- app/src/lib/scrollReveal.ts | 58 +- app/src/lib/types.ts | 226 +++--- app/src/routes/+layout.server.ts | 46 +- app/src/routes/+layout.svelte | 70 +- app/src/routes/+page.server.ts | 66 +- app/src/routes/[slug]/+page.server.ts | 48 +- app/src/routes/[slug]/+page.svelte | 20 +- app/src/routes/admin/+layout.server.ts | 10 +- app/src/routes/admin/+layout.svelte | 188 ++--- app/src/routes/admin/api/export/+server.ts | 176 ++--- app/src/routes/admin/api/import/+server.ts | 278 +++---- app/src/routes/admin/api/upload/+server.ts | 54 +- app/src/routes/admin/calendar/+page.server.ts | 108 +-- app/src/routes/admin/calendar/+page.svelte | 472 ++++++------ app/src/routes/admin/globals/+page.server.ts | 62 +- app/src/routes/admin/globals/+page.svelte | 192 ++--- app/src/routes/admin/login/+page.server.ts | 54 +- app/src/routes/admin/login/+page.svelte | 52 +- app/src/routes/admin/pages/+page.server.ts | 58 +- app/src/routes/admin/pages/+page.svelte | 130 ++-- .../routes/admin/pages/[slug]/+page.server.ts | 50 +- .../routes/admin/pages/[slug]/+page.svelte | 208 +++--- app/src/routes/preview/+page.svelte | 50 +- backups/cms-export-2026-05-27.json | 692 +++++++++--------- docker-compose.yml | 70 +- pb_schema.json | 588 +++++++-------- 57 files changed, 4174 insertions(+), 4139 deletions(-) create mode 100644 Caddyfile diff --git a/.dockerignore b/.dockerignore index 2ba1c2d..b416a3a 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,6 +1,6 @@ -node_modules -app/node_modules -app/.svelte-kit -app/build -.git -pocketbase/pb_data +node_modules +app/node_modules +app/.svelte-kit +app/build +.git +pocketbase/pb_data diff --git a/.env.example b/.env.example index 37e2089..91c4dfe 100644 --- a/.env.example +++ b/.env.example @@ -1,2 +1,2 @@ -PUBLIC_POCKETBASE_URL=http://localhost:8090 -POCKETBASE_INTERNAL_URL=http://localhost:8090 +PUBLIC_POCKETBASE_URL=http://localhost:8090 +POCKETBASE_INTERNAL_URL=http://localhost:8090 diff --git a/AGENTS.md b/AGENTS.md index 8d67451..5347ea2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,105 +1,106 @@ -# Massage Studio Website CMS — Agent Guidelines - -## Stack - -- **SvelteKit 2** (SSR, Svelte 5 runes mode) — all `.svelte` files use `$state`, `$derived`, `$props()` etc. -- **PocketBase** — REST API via the `pocketbase` SDK (v0.26). Auth, DB, and image storage. -- **Tailwind CSS v4** + **DaisyUI 5** — utility-first CSS with DaisyUI components for admin; custom theme for the public site. -- **Docker Compose** — two services: `app` (SvelteKit) and `pocketbase`. - -## Project Structure - -``` -app/ # SvelteKit application -├── src/ -│ ├── lib/ -│ │ ├── admin/ # Admin UI components (BlockList, editors) -│ │ ├── blocks/ # Public block renderers (one per BlockType) -│ │ ├── components/ # Header.svelte, Footer.svelte -│ │ ├── pb.ts # PocketBase client factory + helpers -│ │ └── types.ts # ContentBlock, PageRecord, HeaderGlobal, FooterGlobal -│ ├── routes/ -│ │ ├── +layout.svelte # Root layout (admin vs public shell) -│ │ ├── +page.svelte # Home page (slug=home) -│ │ ├── [slug]/ # Dynamic CMS pages -│ │ ├── admin/ # Admin area (login, pages, globals) -│ │ └── preview/ # Draft preview via sessionStorage -│ └── app.css # Tailwind + DaisyUI + custom theme -├── static/ # Static assets -├── build/ # Production build output -├── svelte.config.js # Adapter-node, runes mode forced -├── vite.config.ts # Tailwind v4 + SvelteKit plugins -└── package.json -pocketbase/pb_data/ # PocketBase data (mounted volume-mounted) -docker-compose.yml # app + pocketbase services -Dockerfile # Multi-stage Node 22 build -``` - -## Key Conventions - -### Svelte 5 Runes Mode -All components use Svelte 5 runes syntax — **never** `export let`, `$:`, or `on:click`. Use: -- `$props()` for component props -- `$state()` for reactive local state -- `$derived()` for computed values -- `$effect()` / `onMount` for side effects -- `{@render children()}` for slots -- `onclick={handler}` (not `on:click`) - -### Block System -Pages are composed of `ContentBlock[]`. Each block has `{ id, type, data }`. Block types are defined in `$lib/types.ts`: -`text | image | image_text | timeline | testimonials | services | cta | spacer | horizontal_cards` - -- **Public renderers**: `$lib/blocks/Block.svelte` — one per type, receives `data` prop. Currently active: `TextBlock`, `ImageTextBlock`, `TimelineBlock`, `HeroBlock`. -- **Admin editors**: `$lib/admin/editors/BlockEditor.svelte` — switches editor UI by type -- **Defaults**: `$lib/admin/blockDefaults.ts` — `createBlock(type)` generates a new block with sensible defaults -- **Block list**: `$lib/admin/BlockList.svelte` — draggable reorder, select, delete - -To add a new block type: add to `BlockType` union in `types.ts`, create renderer in `$lib/blocks/`, add editor case in `BlockEditor.svelte`, add default in `blockDefaults.ts`, add import in `BlockRenderer.svelte`. - -### PocketBase Integration -- Client created in `hooks.server.ts` (`event.locals.pb`) — injected per-request with auth cookie -- `$lib/pb.ts` exports `createPocketBase()`, `getFileUrl()`, `uploadMedia()` -- Collections: `pages` (slug, title, blocks[], published), `globals` (key, data), `media` (file, alt) -- Server load functions use `locals.pb.collection('pages').getFirstListItem()` - -### Styling -- **Public site**: Custom theme via `@theme` in `app.css` — colors: `warm`, `charcoal`, `sage`, `sage-dark`, `terracotta`. Fonts: `DM Sans` (body), `Playfair Display` (headings). -- **Admin area**: DaisyUI utility classes (`btn`, `card`, `input`, `select`, `rounded-box`, etc.) -- **Prose**: `.prose-wellness` class for rich text content styling - -### Routing -- `+layout.server.ts` fetches header/footer globals for every public page -- `+page.server.ts` for home fetches `slug = "home" && published = true` -- `[slug]/+page.server.ts` fetches by dynamic slug -- Admin routes protected in `hooks.server.ts` — redirects to `/admin/login` if unauthenticated - -## Build & Dev Commands - -```sh -# Development (from app/) -cd app -npm install -npm run dev # http://localhost:5173 - -# Production build -npm run build - -# Type checking -npm run check - -# Docker full stack -docker compose up --build -# App: http://localhost:3000 -# PocketBase admin: http://localhost:8090/_/ - -# PocketBase only (for local dev) -docker compose up pocketbase -``` - -## Environment - -- `PUBLIC_POCKETBASE_URL` — public-facing PocketBase URL (default `http://localhost:8090`) -- `POCKETBASE_INTERNAL_URL` — internal Docker network URL (`http://pocketbase:80`) -- `ORIGIN` — SvelteKit origin for SSR (`http://localhost:3000`) -- Copy `app/.env.example` → `app/.env` for local dev +# Massage Studio Website CMS — Agent Guidelines + +## Stack + +- **SvelteKit 2** (SSR, Svelte 5 runes mode) — all `.svelte` files use `$state`, `$derived`, `$props()` etc. +- **PocketBase** — REST API via the `pocketbase` SDK (v0.26). Auth, DB, and image storage. +- **Tailwind CSS v4** + **DaisyUI 5** — utility-first CSS with DaisyUI components for admin; custom theme for the public site. +- **Docker Compose** — three services: `app` (SvelteKit), `pocketbase`, and `caddy` (reverse proxy). + +## Project Structure + +``` +app/ # SvelteKit application +├── src/ +│ ├── lib/ +│ │ ├── admin/ # Admin UI components (BlockList, editors) +│ │ ├── blocks/ # Public block renderers (one per BlockType) +│ │ ├── components/ # Header.svelte, Footer.svelte +│ │ ├── pb.ts # PocketBase client factory + helpers +│ │ └── types.ts # ContentBlock, PageRecord, HeaderGlobal, FooterGlobal +│ ├── routes/ +│ │ ├── +layout.svelte # Root layout (admin vs public shell) +│ │ ├── +page.svelte # Home page (slug=home) +│ │ ├── [slug]/ # Dynamic CMS pages +│ │ ├── admin/ # Admin area (login, pages, globals) +│ │ └── preview/ # Draft preview via sessionStorage +│ └── app.css # Tailwind + DaisyUI + custom theme +├── static/ # Static assets +├── build/ # Production build output +├── svelte.config.js # Adapter-node, runes mode forced +├── vite.config.ts # Tailwind v4 + SvelteKit plugins +└── package.json +pocketbase/pb_data/ # PocketBase data (mounted volume-mounted) +docker-compose.yml # app + pocketbase services +Dockerfile # Multi-stage Node 22 build +``` + +## Key Conventions + +### Svelte 5 Runes Mode +All components use Svelte 5 runes syntax — **never** `export let`, `$:`, or `on:click`. Use: +- `$props()` for component props +- `$state()` for reactive local state +- `$derived()` for computed values +- `$effect()` / `onMount` for side effects +- `{@render children()}` for slots +- `onclick={handler}` (not `on:click`) + +### Block System +Pages are composed of `ContentBlock[]`. Each block has `{ id, type, data }`. Block types are defined in `$lib/types.ts`: +`text | image | image_text | timeline | testimonials | services | cta | spacer | horizontal_cards` + +- **Public renderers**: `$lib/blocks/Block.svelte` — one per type, receives `data` prop. Currently active: `TextBlock`, `ImageTextBlock`, `TimelineBlock`, `HeroBlock`. +- **Admin editors**: `$lib/admin/editors/BlockEditor.svelte` — switches editor UI by type +- **Defaults**: `$lib/admin/blockDefaults.ts` — `createBlock(type)` generates a new block with sensible defaults +- **Block list**: `$lib/admin/BlockList.svelte` — draggable reorder, select, delete + +To add a new block type: add to `BlockType` union in `types.ts`, create renderer in `$lib/blocks/`, add editor case in `BlockEditor.svelte`, add default in `blockDefaults.ts`, add import in `BlockRenderer.svelte`. + +### PocketBase Integration +- Client created in `hooks.server.ts` (`event.locals.pb`) — injected per-request with auth cookie +- `$lib/pb.ts` exports `createPocketBase()`, `getFileUrl()`, `uploadMedia()` +- Collections: `pages` (slug, title, blocks[], published), `globals` (key, data), `media` (file, alt) +- Server load functions use `locals.pb.collection('pages').getFirstListItem()` + +### Styling +- **Public site**: Custom theme via `@theme` in `app.css` — colors: `warm`, `charcoal`, `sage`, `sage-dark`, `terracotta`. Fonts: `DM Sans` (body), `Playfair Display` (headings). +- **Admin area**: DaisyUI utility classes (`btn`, `card`, `input`, `select`, `rounded-box`, etc.) +- **Prose**: `.prose-wellness` class for rich text content styling + +### Routing +- `+layout.server.ts` fetches header/footer globals for every public page +- `+page.server.ts` for home fetches `slug = "home" && published = true` +- `[slug]/+page.server.ts` fetches by dynamic slug +- Admin routes protected in `hooks.server.ts` — redirects to `/admin/login` if unauthenticated + +## Build & Dev Commands + +```sh +# Development (from app/) +cd app +npm install +npm run dev # http://localhost:5173 + +# Production build +npm run build + +# Type checking +npm run check + +# Docker full stack (single entry point on port 8080) +docker compose up --build +# App + PocketBase via Caddy: http://localhost:8080 +# PocketBase admin: http://localhost:8080/_/ + +# PocketBase only (for local dev outside Docker) +docker compose up pocketbase +# Direct access: http://localhost:8090/_/ +``` + +## Environment + +- `PUBLIC_POCKETBASE_URL` — public-facing PocketBase URL, now accessed through the Caddy reverse proxy (default `http://localhost:8080`) +- `POCKETBASE_INTERNAL_URL` — internal Docker network URL (`http://pocketbase:80`) +- `ORIGIN` — SvelteKit origin for SSR (`http://localhost:8080`) +- Copy `app/.env.example` → `app/.env` for local dev diff --git a/CONTRACT.md b/CONTRACT.md index 7fbf1d3..1b3212f 100644 --- a/CONTRACT.md +++ b/CONTRACT.md @@ -1,208 +1,208 @@ -# SOFTWARE DEVELOPMENT AGREEMENT - -This Software Development Agreement ("Agreement") is entered into on [DATE] - -between - -**Developer:** -[YOUR NAME] -[ADDRESS] -[IČO / REGISTRATION NUMBER, IF APPLICABLE] -Email: [EMAIL] - -and - -**Client:** -[CLIENT NAME] -[CLIENT ADDRESS] -Email: [EMAIL] - ---- - -## 1. Subject of the Agreement - -The Developer agrees to design and develop a new website for the Client, built on the Developer's custom CMS platform. - -The scope of work includes: - -- implementation of a custom CMS, including a block-based page builder allowing the Client to create and manage static pages independently, -- move the current website (www.evashafik.com) from Tilda to the new CMS system, -- a services and pricing catalogue (add, edit, hide or reactivate services including name, description, duration and price), -- a an editable calendar displaying practitioner availability, events, workshops and courses, -- a custom booking system for the Client's services and treatments, including service selection, time slot availability, optional add-ons and automatic price calculation, -- Stripe integration for online payment processing, -- booking confirmations and notifications for both the Client and end customers, - - integration with Client's google calendar -- buffer time and minimum lead time configuration per service, -- co-worker profiles with direct contact information (no online booking required for co-workers), -- deployment and configuration of hosting infrastructure under the Client's ownership, -- migration of existing content necessary for operation of the website. - -Any functionality not explicitly listed above shall be considered outside the scope of this Agreement and may be subject to a separate agreement or additional fees. - ---- - -## 2. Project Duration - -The estimated duration of the project is five (5) months from the Effective Date of this Agreement. - -The parties acknowledge that this timeline is an estimate and may be extended in accordance with Section 8 (Client Cooperation). - -If the Developer anticipates that the project cannot be completed within the estimated timeline, the Developer shall notify the Client in writing as soon as reasonably practicable. The parties shall then agree in good faith on a revised timeline. - ---- - -## 3. Compensation - -The total project fee shall be: - -**EUR 2,500** - -The Client shall pay the fee in five monthly installments of: - -**EUR 500 per month** - -Invoices shall be due within fourteen (14) days of issuance. - -In the event of late payment, the Developer shall be entitled to suspend work until all outstanding amounts have been paid. - -The Developer is not obligated to continue providing services while any invoice remains overdue. - -Any suspension caused by late payment shall automatically extend project deadlines by the duration of the suspension. - ---- - -## 4. Hosting - -Hosting services, domain registrations, and third-party services shall be registered and owned by the Client. - -The Developer will assist with setup, configuration, and administration of such services. - -The Client shall be solely responsible for all fees charged by hosting providers, registrars, and third-party service providers. - ---- - -## 5. Intellectual Property - -Upon full payment of all amounts due under this Agreement, the Client shall own the project-specific code and assets created exclusively for this project, including custom templates, design implementation, and project-specific configuration. - -The Client acknowledges that the delivered website is built on top of the Developer's general-purpose CMS platform, which contains components intended for reuse across multiple projects. The Developer retains full ownership of that platform, including its core framework, modules, libraries, and underlying architecture. - -The Client receives a perpetual, non-exclusive license to run the platform as part of their website. This license allows the Client to use, modify, and maintain the website freely, including engaging other developers to work on it. - -The Developer retains the right to use, improve, and build commercial products from the CMS platform independently of this project. - ---- - -## 6. Content Management - -The CMS is designed to allow the Client to manage routine content independently without developer involvement. The following tasks can be performed directly by the Client: - -- adding, editing, deleting and hiding co-worker profiles, -- adding, editing, deleting and hiding services and pricing, -- adding, editing, deleting and managing events, workshops and courses in the calendar, -- creating new pages using the block-based page builder. - -The following tasks will typically require developer involvement: - -- new third-party integrations, -- structural or architectural changes to the website, -- new features or functionality outside the current scope, -- custom development beyond standard CMS capabilities. - -Future developer assistance will be available at an agreed hourly rate or fixed price per task, as discussed separately. - ---- - -## 7. Change Requests - -Any requests that materially extend or alter the agreed scope of work may be treated as additional work and may require a separate agreement regarding scope, timeline, and compensation. - ---- - -## 8. Client Cooperation - -The Client agrees to provide all necessary information, materials, approvals, and feedback required for completion of the project. - -If the Client fails to respond to requests for information, approvals, or feedback for a period exceeding thirty (30) consecutive days: - -- all project deadlines shall be automatically extended by at least the duration of such delay, -- the Developer shall not be considered in breach of any delivery deadlines affected by such delay. - -The Developer may pause work until the required cooperation is provided. - -Communication by email or WhatsApp shall be considered sufficient for all approvals, feedback, and project-related decisions. - ---- - -## 9. Acceptance - -The Client shall review delivered work within fourteen (14) days after delivery. - -If no substantial objections are communicated within that period, the delivered work shall be deemed accepted. - ---- - -## 10. Termination - -Either party may terminate this Agreement by written notice. - -In the event of termination, the Client shall pay for all work completed up to the termination date. - -Any payments already made are non-refundable for work already performed. - ---- - -## 11. Limitation of Liability - -The Developer shall not be liable for: - -- downtime caused by third-party providers, -- hosting provider failures, -- domain registrar failures, -- third-party software or service outages, -- indirect or consequential damages. - -The Developer's total liability under this Agreement shall not exceed the total amount paid by the Client under this Agreement. - ---- - -## 12. Governing Law and Jurisdiction - -This Agreement shall be governed by and construed in accordance with the laws of the Czech Republic. - -Any disputes arising out of or in connection with this Agreement shall be subject to the exclusive jurisdiction of the courts of the Czech Republic. - ---- - -## 13. Entire Agreement - -This Agreement constitutes the entire agreement between the parties and supersedes all prior discussions, negotiations, and understandings regarding the subject matter herein. - -Any amendments must be made in writing and agreed by both parties. - ---- - -## 14. Data Protection - -The Developer shall implement standard GDPR-compliant features within the website and booking system, including consent checkboxes for the collection and processing of personal data, a privacy policy page, and tools allowing the Client to manage customer data in accordance with data subject rights (including the ability to edit, export, and delete customer records). The Client shall be solely responsible for ensuring the content of the privacy policy is accurate and up to date, and that their overall use of the website and collected data complies with applicable data protection laws. - ---- - -**Developer** - -Name: __________________________ - -Signature: ______________________ - -Date: ___________________________ - ---- - -**Client** - -Name: __________________________ - -Signature: ______________________ - +# SOFTWARE DEVELOPMENT AGREEMENT + +This Software Development Agreement ("Agreement") is entered into on [DATE] + +between + +**Developer:** +[YOUR NAME] +[ADDRESS] +[IČO / REGISTRATION NUMBER, IF APPLICABLE] +Email: [EMAIL] + +and + +**Client:** +[CLIENT NAME] +[CLIENT ADDRESS] +Email: [EMAIL] + +--- + +## 1. Subject of the Agreement + +The Developer agrees to design and develop a new website for the Client, built on the Developer's custom CMS platform. + +The scope of work includes: + +- implementation of a custom CMS, including a block-based page builder allowing the Client to create and manage static pages independently, +- move the current website (www.evashafik.com) from Tilda to the new CMS system, +- a services and pricing catalogue (add, edit, hide or reactivate services including name, description, duration and price), +- a an editable calendar displaying practitioner availability, events, workshops and courses, +- a custom booking system for the Client's services and treatments, including service selection, time slot availability, optional add-ons and automatic price calculation, +- Stripe integration for online payment processing, +- booking confirmations and notifications for both the Client and end customers, + - integration with Client's google calendar +- buffer time and minimum lead time configuration per service, +- co-worker profiles with direct contact information (no online booking required for co-workers), +- deployment and configuration of hosting infrastructure under the Client's ownership, +- migration of existing content necessary for operation of the website. + +Any functionality not explicitly listed above shall be considered outside the scope of this Agreement and may be subject to a separate agreement or additional fees. + +--- + +## 2. Project Duration + +The estimated duration of the project is five (5) months from the Effective Date of this Agreement. + +The parties acknowledge that this timeline is an estimate and may be extended in accordance with Section 8 (Client Cooperation). + +If the Developer anticipates that the project cannot be completed within the estimated timeline, the Developer shall notify the Client in writing as soon as reasonably practicable. The parties shall then agree in good faith on a revised timeline. + +--- + +## 3. Compensation + +The total project fee shall be: + +**EUR 2,500** + +The Client shall pay the fee in five monthly installments of: + +**EUR 500 per month** + +Invoices shall be due within fourteen (14) days of issuance. + +In the event of late payment, the Developer shall be entitled to suspend work until all outstanding amounts have been paid. + +The Developer is not obligated to continue providing services while any invoice remains overdue. + +Any suspension caused by late payment shall automatically extend project deadlines by the duration of the suspension. + +--- + +## 4. Hosting + +Hosting services, domain registrations, and third-party services shall be registered and owned by the Client. + +The Developer will assist with setup, configuration, and administration of such services. + +The Client shall be solely responsible for all fees charged by hosting providers, registrars, and third-party service providers. + +--- + +## 5. Intellectual Property + +Upon full payment of all amounts due under this Agreement, the Client shall own the project-specific code and assets created exclusively for this project, including custom templates, design implementation, and project-specific configuration. + +The Client acknowledges that the delivered website is built on top of the Developer's general-purpose CMS platform, which contains components intended for reuse across multiple projects. The Developer retains full ownership of that platform, including its core framework, modules, libraries, and underlying architecture. + +The Client receives a perpetual, non-exclusive license to run the platform as part of their website. This license allows the Client to use, modify, and maintain the website freely, including engaging other developers to work on it. + +The Developer retains the right to use, improve, and build commercial products from the CMS platform independently of this project. + +--- + +## 6. Content Management + +The CMS is designed to allow the Client to manage routine content independently without developer involvement. The following tasks can be performed directly by the Client: + +- adding, editing, deleting and hiding co-worker profiles, +- adding, editing, deleting and hiding services and pricing, +- adding, editing, deleting and managing events, workshops and courses in the calendar, +- creating new pages using the block-based page builder. + +The following tasks will typically require developer involvement: + +- new third-party integrations, +- structural or architectural changes to the website, +- new features or functionality outside the current scope, +- custom development beyond standard CMS capabilities. + +Future developer assistance will be available at an agreed hourly rate or fixed price per task, as discussed separately. + +--- + +## 7. Change Requests + +Any requests that materially extend or alter the agreed scope of work may be treated as additional work and may require a separate agreement regarding scope, timeline, and compensation. + +--- + +## 8. Client Cooperation + +The Client agrees to provide all necessary information, materials, approvals, and feedback required for completion of the project. + +If the Client fails to respond to requests for information, approvals, or feedback for a period exceeding thirty (30) consecutive days: + +- all project deadlines shall be automatically extended by at least the duration of such delay, +- the Developer shall not be considered in breach of any delivery deadlines affected by such delay. + +The Developer may pause work until the required cooperation is provided. + +Communication by email or WhatsApp shall be considered sufficient for all approvals, feedback, and project-related decisions. + +--- + +## 9. Acceptance + +The Client shall review delivered work within fourteen (14) days after delivery. + +If no substantial objections are communicated within that period, the delivered work shall be deemed accepted. + +--- + +## 10. Termination + +Either party may terminate this Agreement by written notice. + +In the event of termination, the Client shall pay for all work completed up to the termination date. + +Any payments already made are non-refundable for work already performed. + +--- + +## 11. Limitation of Liability + +The Developer shall not be liable for: + +- downtime caused by third-party providers, +- hosting provider failures, +- domain registrar failures, +- third-party software or service outages, +- indirect or consequential damages. + +The Developer's total liability under this Agreement shall not exceed the total amount paid by the Client under this Agreement. + +--- + +## 12. Governing Law and Jurisdiction + +This Agreement shall be governed by and construed in accordance with the laws of the Czech Republic. + +Any disputes arising out of or in connection with this Agreement shall be subject to the exclusive jurisdiction of the courts of the Czech Republic. + +--- + +## 13. Entire Agreement + +This Agreement constitutes the entire agreement between the parties and supersedes all prior discussions, negotiations, and understandings regarding the subject matter herein. + +Any amendments must be made in writing and agreed by both parties. + +--- + +## 14. Data Protection + +The Developer shall implement standard GDPR-compliant features within the website and booking system, including consent checkboxes for the collection and processing of personal data, a privacy policy page, and tools allowing the Client to manage customer data in accordance with data subject rights (including the ability to edit, export, and delete customer records). The Client shall be solely responsible for ensuring the content of the privacy policy is accurate and up to date, and that their overall use of the website and collected data complies with applicable data protection laws. + +--- + +**Developer** + +Name: __________________________ + +Signature: ______________________ + +Date: ___________________________ + +--- + +**Client** + +Name: __________________________ + +Signature: ______________________ + Date: ___________________________ \ No newline at end of file diff --git a/Caddyfile b/Caddyfile new file mode 100644 index 0000000..4627014 --- /dev/null +++ b/Caddyfile @@ -0,0 +1,17 @@ +# Reverse proxy — single port for both the SvelteKit app and PocketBase +# Route: /api/* and /_/* → PocketBase +# everything else → SvelteKit app + +:8080 { + handle /api/* { + reverse_proxy pocketbase:80 + } + + handle /_/* { + reverse_proxy pocketbase:80 + } + + handle { + reverse_proxy app:3000 + } +} \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index e8a6f66..708ee7e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,23 +1,23 @@ -# syntax=docker/dockerfile:1.7 - -FROM node:22-alpine AS build -WORKDIR /app -ENV NPM_CONFIG_AUDIT=false \ - NPM_CONFIG_FUND=false \ - NPM_CONFIG_PROGRESS=false -COPY app/package*.json ./ -RUN --mount=type=cache,target=/root/.npm npm ci --ignore-scripts --no-audit --no-fund -COPY app/ ./ -RUN npm run build - -FROM node:22-alpine -WORKDIR /app -ENV NODE_ENV=production \ - NPM_CONFIG_AUDIT=false \ - NPM_CONFIG_FUND=false \ - NPM_CONFIG_PROGRESS=false -COPY --from=build /app/build ./build -COPY --from=build /app/package*.json ./ -RUN --mount=type=cache,target=/root/.npm npm ci --omit=dev --ignore-scripts --no-audit --no-fund -EXPOSE 3000 -CMD ["node", "build"] +# syntax=docker/dockerfile:1.7 + +FROM node:22-alpine AS build +WORKDIR /app +ENV NPM_CONFIG_AUDIT=false \ + NPM_CONFIG_FUND=false \ + NPM_CONFIG_PROGRESS=false +COPY app/package*.json ./ +RUN --mount=type=cache,target=/root/.npm npm ci --ignore-scripts --no-audit --no-fund +COPY app/ ./ +RUN npm run build + +FROM node:22-alpine +WORKDIR /app +ENV NODE_ENV=production \ + NPM_CONFIG_AUDIT=false \ + NPM_CONFIG_FUND=false \ + NPM_CONFIG_PROGRESS=false +COPY --from=build /app/build ./build +COPY --from=build /app/package*.json ./ +RUN --mount=type=cache,target=/root/.npm npm ci --omit=dev --ignore-scripts --no-audit --no-fund +EXPOSE 3000 +CMD ["node", "build"] diff --git a/README.md b/README.md index 3d90779..223b11f 100644 --- a/README.md +++ b/README.md @@ -1,112 +1,115 @@ -# Massage Studio Website CMS - -A full-stack SvelteKit CMS for a single-operator massage studio. PocketBase provides auth, database records, and image storage. The public site is warm and minimal; the admin UI uses DaisyUI components. - -## Stack - -- SvelteKit + SSR -- PocketBase REST API via the `pocketbase` SDK -- Tailwind CSS v4 + DaisyUI -- Docker Compose with two services: `app` and `pocketbase` - -## Local development - -1. Install Node.js `22.x` or another version accepted by SvelteKit's Vite plugin. -2. Copy the app env file: - ```sh - cp app/.env.example app/.env - ``` -3. Start PocketBase on port `8090`. With Docker: - ```sh - docker compose up pocketbase - ``` -4. In another terminal: - ```sh - cd app - npm install - npm run dev - ``` -5. Visit `http://localhost:5173`. - -## Docker Compose - -Run the full stack: - -```sh -docker compose up --build -``` - -If dependency installation is slow on the first build, enable BuildKit explicitly: - -```sh -DOCKER_BUILDKIT=1 docker compose build --progress=plain app -docker compose up -``` - -Subsequent builds reuse the npm cache declared in the `Dockerfile`. - -- Public SvelteKit app: `http://localhost:3000` -- PocketBase admin UI: `http://localhost:8090/_/` - -The app container uses two PocketBase URLs: - -- `POCKETBASE_INTERNAL_URL=http://pocketbase:80` for server-side SvelteKit calls from the app container when using the included `spectado/pocketbase` image. -- `PUBLIC_POCKETBASE_URL=http://localhost:8090` for browser-side admin uploads and public file URLs during local Docker development. - -In production, set `PUBLIC_POCKETBASE_URL` to the browser-accessible PocketBase URL, or to the reverse-proxied PocketBase path/origin you expose publicly. - -## PocketBase setup - -1. Open `http://localhost:8090/_/`. -2. Create the first PocketBase admin user when prompted. -3. Import `pb_schema.json` from the PocketBase admin UI collection settings/import flow. This file uses the newer PocketBase `fields` schema format; if PocketBase still reports `Invalid collections configuration`, create the three collections manually using the fields below. -4. Create starter records: - - `pages`: slug `home`, title `Home`, `published: true`, and a blocks JSON array. - - `globals`: key `header`, data matching the header JSON in the project prompt. - - `globals`: key `footer`, data matching the footer JSON in the project prompt. - -If the `globals` records do not exist, the app falls back to safe defaults and the admin globals page will create them. - -### Manual collection fields fallback - -If schema import fails because of a PocketBase version mismatch, create these collections manually: - -- `pages` - - `slug`: text, required, unique - - `title`: text, required - - `blocks`: json - - `published`: bool -- `globals` - - `key`: text, required, unique - - `data`: json -- `media` - - `file`: file, required, max select `1`, image mime types - - `alt`: text - -## Authentication - -Admin routes live under `/admin`. Login accepts either: - -- a PocketBase admin account, or -- a record from a `users` auth collection if you create one. - -All `/admin` routes except `/admin/login` are guarded in `src/hooks.server.ts`. - -## CMS routes - -- `/admin/login` — sign in -- `/admin/pages` — list/create pages -- `/admin/pages/[slug]` — block editor with draft preview -- `/admin/globals` — header/footer editor - -## Public routes - -- `/` renders `pages.slug = "home"` -- `/[slug]` renders any other published page -- Unpublished pages return `404` - -## Notes - -- Admin image uploads create records in the `media` collection and store PocketBase file URLs in block JSON. -- Draft preview writes current blocks to `sessionStorage` and opens `/preview` in an iframe. -- The page editor includes draggable reordering using native HTML drag events for compatibility; the requested DnD packages are installed and can be swapped in later if desired. +# Massage Studio Website CMS + +A full-stack SvelteKit CMS for a single-operator massage studio. PocketBase provides auth, database records, and image storage. The public site is warm and minimal; the admin UI uses DaisyUI components. + +## Stack + +- SvelteKit + SSR +- PocketBase REST API via the `pocketbase` SDK +- Tailwind CSS v4 + DaisyUI +- Docker Compose with three services: `app`, `pocketbase`, and `caddy` (reverse proxy) + +## Local development + +1. Install Node.js `22.x` or another version accepted by SvelteKit's Vite plugin. +2. Copy the app env file: + ```sh + cp app/.env.example app/.env + ``` +3. Start PocketBase on port `8090`. With Docker: + ```sh + docker compose up pocketbase + ``` +4. In another terminal: + ```sh + cd app + npm install + npm run dev + ``` +5. Visit `http://localhost:5173`. + +> **Note:** During local development (outside Docker), PocketBase is accessed directly at `http://localhost:8090`. When running the full Docker stack, everything goes through the Caddy reverse proxy on port `8080`. + +## Docker Compose + +Run the full stack: + +```sh +docker compose up --build +``` + +If dependency installation is slow on the first build, enable BuildKit explicitly: + +```sh +DOCKER_BUILDKIT=1 docker compose build --progress=plain app +docker compose up +``` + +Subsequent builds reuse the npm cache declared in the `Dockerfile`. + +- Single entry point (Caddy reverse proxy): **`http://localhost:8080`** + - SvelteKit app: `http://localhost:8080/` (or any non-API path) + - PocketBase admin UI: `http://localhost:8080/_/` + - PocketBase REST API: `http://localhost:8080/api/` +- PocketBase direct access (internal only, not exposed): `http://localhost:8090` + +The app container uses two PocketBase URLs: + +- `POCKETBASE_INTERNAL_URL=http://pocketbase:80` for server-side SvelteKit calls from the app container when using the included `spectado/pocketbase` image. +- `PUBLIC_POCKETBASE_URL=http://localhost:8080` for browser-side admin uploads and public file URLs. Since the Caddy reverse proxy routes `/api/*` to PocketBase, the public URL points to the proxy. + +## PocketBase setup + +1. Open `http://localhost:8080/_/` (or `http://localhost:8090/_/` for direct access). +2. Create the first PocketBase admin user when prompted. +3. Import `pb_schema.json` from the PocketBase admin UI collection settings/import flow. This file uses the newer PocketBase `fields` schema format; if PocketBase still reports `Invalid collections configuration`, create the three collections manually using the fields below. +4. Create starter records: + - `pages`: slug `home`, title `Home`, `published: true`, and a blocks JSON array. + - `globals`: key `header`, data matching the header JSON in the project prompt. + - `globals`: key `footer`, data matching the footer JSON in the project prompt. + +If the `globals` records do not exist, the app falls back to safe defaults and the admin globals page will create them. + +### Manual collection fields fallback + +If schema import fails because of a PocketBase version mismatch, create these collections manually: + +- `pages` + - `slug`: text, required, unique + - `title`: text, required + - `blocks`: json + - `published`: bool +- `globals` + - `key`: text, required, unique + - `data`: json +- `media` + - `file`: file, required, max select `1`, image mime types + - `alt`: text + +## Authentication + +Admin routes live under `/admin`. Login accepts either: + +- a PocketBase admin account, or +- a record from a `users` auth collection if you create one. + +All `/admin` routes except `/admin/login` are guarded in `src/hooks.server.ts`. + +## CMS routes + +- `/admin/login` — sign in +- `/admin/pages` — list/create pages +- `/admin/pages/[slug]` — block editor with draft preview +- `/admin/globals` — header/footer editor + +## Public routes + +- `/` renders `pages.slug = "home"` +- `/[slug]` renders any other published page +- Unpublished pages return `404` + +## Notes + +- Admin image uploads create records in the `media` collection and store PocketBase file URLs in block JSON. +- Draft preview writes current blocks to `sessionStorage` and opens `/preview` in an iframe. +- The page editor includes draggable reordering using native HTML drag events for compatibility; the requested DnD packages are installed and can be swapped in later if desired. diff --git a/app/.env.example b/app/.env.example index aced3f0..29618d2 100644 --- a/app/.env.example +++ b/app/.env.example @@ -1 +1 @@ -PUBLIC_POCKETBASE_URL=http://localhost:8090 +PUBLIC_POCKETBASE_URL=http://localhost:8080 diff --git a/app/src/app.css b/app/src/app.css index e40a01a..84c1665 100644 --- a/app/src/app.css +++ b/app/src/app.css @@ -1,140 +1,140 @@ -@import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=Playfair+Display:wght@600;700&display=swap'); -@import 'tailwindcss'; -@plugin 'daisyui' { - themes: light --default; -} - -@theme { - --font-sans: 'DM Sans', ui-sans-serif, system-ui, sans-serif; - --font-serif: 'Playfair Display', Georgia, serif; - --color-warm: var(--color-bg, #faf8f5); - --color-charcoal: var(--color-heading, #2c2c2c); - --color-sage: var(--color-primary, #8a9a7b); - --color-sage-dark: color-mix(in srgb, var(--color-primary, #8a9a7b) 80%, #000); - --color-terracotta: var(--color-accent, #c9825f); -} - -@keyframes shrink { - from { scale: 0 1; } - to { scale: 1 1; } -} - -.delete-fill { - position: absolute; - inset: 0; - background: transparent; - transform-origin: left; -} - -.delete-fill.animating { - animation: shrink 1s ease-in-out forwards; - background: var(--error, #f43f5e); -} - -.btn.delete-holding { - color: white !important; -} - -.btn.delete-holding .text-error { - color: white !important; -} - -:root { - --fg-heading: var(--color-heading, #2c2c2c); - --fg-subheading: var(--color-subheading, #4a4a4a); - --fg-body: var(--color-text, #2c2c2c); - background: var(--color-bg, #faf8f5); - color: var(--fg-body); - font-family: 'DM Sans', ui-sans-serif, system-ui, sans-serif; -} - -/* ── Foreground colour utilities (set per-block via BackgroundWrapper) ── */ -.text-fg-body { color: var(--fg-body, #2c2c2c); } -.text-fg-body\/85 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 85%, transparent); } -.text-fg-body\/80 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 80%, transparent); } -.text-fg-body\/75 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 75%, transparent); } -.text-fg-body\/70 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 70%, transparent); } -.text-fg-body\/60 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 60%, transparent); } -.text-fg-heading { color: var(--fg-heading, #2c2c2c); } -.text-fg-subheading { color: var(--fg-subheading, #4a4a4a); } -.text-fg-subheading\/85 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 85%, transparent); } -.text-fg-subheading\/80 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 80%, transparent); } -.text-fg-subheading\/75 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 75%, transparent); } -.text-fg-subheading\/70 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 70%, transparent); } -.text-fg-subheading\/60 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 60%, transparent); } - -body { - min-height: 100vh; - margin: 0; - background: - radial-gradient(circle at top left, rgba(var(--color-accent-rgb, 201, 130, 95), 0.1), transparent 36rem), - var(--color-bg, #faf8f5); -} - -h1, -h2, -h3, -h4 { - font-family: 'Playfair Display', Georgia, serif; - color: var(--fg-heading, #2c2c2c); -} - -.prose-wellness p { - margin: 0.75rem 0; - line-height: 1.8; -} - -.prose-wellness h2 { - margin: 1.25rem 0 0.5rem; - font-size: clamp(2rem, 4vw, 3.25rem); - line-height: 1.05; -} - -.prose-wellness h3 { - margin: 1rem 0 0.5rem; - font-size: 1.6rem; -} - -.prose-wellness ul { - list-style: disc; - padding-left: 1.5rem; -} - -.prose-wellness a { - color: color-mix(in srgb, var(--color-primary, #8a9a7b) 90%, #000); - text-decoration: underline; - text-underline-offset: 3px; -} - -/* ── Scroll-reveal animations ── */ -.reveal { - opacity: 0; - transform: translateY(30px); - transition: - opacity 0.7s cubic-bezier(0.25, 0.1, 0.25, 1), - transform 0.7s cubic-bezier(0.25, 0.1, 0.25, 1); -} - -.reveal-visible { - opacity: 1; - transform: translateY(0); -} - -/* ── Hero fade-in stagger ── */ -.animate-fade-in { - opacity: 0; - transform: translateY(20px); - animation: fadeInUp 0.8s cubic-bezier(0.25, 0.1, 0.25, 1) forwards; -} - -@keyframes fadeInUp { - to { - opacity: 1; - transform: translateY(0); - } -} - -/* ── Smooth scroll ── */ -html { - scroll-behavior: smooth; -} +@import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=Playfair+Display:wght@600;700&display=swap'); +@import 'tailwindcss'; +@plugin 'daisyui' { + themes: light --default; +} + +@theme { + --font-sans: 'DM Sans', ui-sans-serif, system-ui, sans-serif; + --font-serif: 'Playfair Display', Georgia, serif; + --color-warm: var(--color-bg, #faf8f5); + --color-charcoal: var(--color-heading, #2c2c2c); + --color-sage: var(--color-primary, #8a9a7b); + --color-sage-dark: color-mix(in srgb, var(--color-primary, #8a9a7b) 80%, #000); + --color-terracotta: var(--color-accent, #c9825f); +} + +@keyframes shrink { + from { scale: 0 1; } + to { scale: 1 1; } +} + +.delete-fill { + position: absolute; + inset: 0; + background: transparent; + transform-origin: left; +} + +.delete-fill.animating { + animation: shrink 1s ease-in-out forwards; + background: var(--error, #f43f5e); +} + +.btn.delete-holding { + color: white !important; +} + +.btn.delete-holding .text-error { + color: white !important; +} + +:root { + --fg-heading: var(--color-heading, #2c2c2c); + --fg-subheading: var(--color-subheading, #4a4a4a); + --fg-body: var(--color-text, #2c2c2c); + background: var(--color-bg, #faf8f5); + color: var(--fg-body); + font-family: 'DM Sans', ui-sans-serif, system-ui, sans-serif; +} + +/* ── Foreground colour utilities (set per-block via BackgroundWrapper) ── */ +.text-fg-body { color: var(--fg-body, #2c2c2c); } +.text-fg-body\/85 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 85%, transparent); } +.text-fg-body\/80 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 80%, transparent); } +.text-fg-body\/75 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 75%, transparent); } +.text-fg-body\/70 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 70%, transparent); } +.text-fg-body\/60 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 60%, transparent); } +.text-fg-heading { color: var(--fg-heading, #2c2c2c); } +.text-fg-subheading { color: var(--fg-subheading, #4a4a4a); } +.text-fg-subheading\/85 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 85%, transparent); } +.text-fg-subheading\/80 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 80%, transparent); } +.text-fg-subheading\/75 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 75%, transparent); } +.text-fg-subheading\/70 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 70%, transparent); } +.text-fg-subheading\/60 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 60%, transparent); } + +body { + min-height: 100vh; + margin: 0; + background: + radial-gradient(circle at top left, rgba(var(--color-accent-rgb, 201, 130, 95), 0.1), transparent 36rem), + var(--color-bg, #faf8f5); +} + +h1, +h2, +h3, +h4 { + font-family: 'Playfair Display', Georgia, serif; + color: var(--fg-heading, #2c2c2c); +} + +.prose-wellness p { + margin: 0.75rem 0; + line-height: 1.8; +} + +.prose-wellness h2 { + margin: 1.25rem 0 0.5rem; + font-size: clamp(2rem, 4vw, 3.25rem); + line-height: 1.05; +} + +.prose-wellness h3 { + margin: 1rem 0 0.5rem; + font-size: 1.6rem; +} + +.prose-wellness ul { + list-style: disc; + padding-left: 1.5rem; +} + +.prose-wellness a { + color: color-mix(in srgb, var(--color-primary, #8a9a7b) 90%, #000); + text-decoration: underline; + text-underline-offset: 3px; +} + +/* ── Scroll-reveal animations ── */ +.reveal { + opacity: 0; + transform: translateY(30px); + transition: + opacity 0.7s cubic-bezier(0.25, 0.1, 0.25, 1), + transform 0.7s cubic-bezier(0.25, 0.1, 0.25, 1); +} + +.reveal-visible { + opacity: 1; + transform: translateY(0); +} + +/* ── Hero fade-in stagger ── */ +.animate-fade-in { + opacity: 0; + transform: translateY(20px); + animation: fadeInUp 0.8s cubic-bezier(0.25, 0.1, 0.25, 1) forwards; +} + +@keyframes fadeInUp { + to { + opacity: 1; + transform: translateY(0); + } +} + +/* ── Smooth scroll ── */ +html { + scroll-behavior: smooth; +} diff --git a/app/src/hooks.server.ts b/app/src/hooks.server.ts index 000fdf6..10588a6 100644 --- a/app/src/hooks.server.ts +++ b/app/src/hooks.server.ts @@ -1,28 +1,28 @@ -import { redirect, type Handle } from '@sveltejs/kit'; -import { env } from '$env/dynamic/private'; -import { createPocketBase } from '$lib/pb'; - -export const handle: Handle = async ({ event, resolve }) => { - event.locals.pb = createPocketBase( - event.request.headers.get('cookie') ?? '', - env.POCKETBASE_INTERNAL_URL || env.PUBLIC_POCKETBASE_URL || 'http://localhost:8090' - ); - event.locals.user = event.locals.pb.authStore.record; - - const path = event.url.pathname; - const isAdminRoute = path.startsWith('/admin'); - const isLoginRoute = path === '/admin/login'; - const isAuthed = event.locals.pb.authStore.isValid; - - if (isAdminRoute && !isLoginRoute && !isAuthed) { - throw redirect(303, '/admin/login'); - } - - if (isLoginRoute && isAuthed) { - throw redirect(303, '/admin/pages'); - } - - const response = await resolve(event); - response.headers.append('set-cookie', event.locals.pb.authStore.exportToCookie({ sameSite: 'lax' }, 'pb_auth')); - return response; -}; +import { redirect, type Handle } from '@sveltejs/kit'; +import { env } from '$env/dynamic/private'; +import { createPocketBase } from '$lib/pb'; + +export const handle: Handle = async ({ event, resolve }) => { + event.locals.pb = createPocketBase( + event.request.headers.get('cookie') ?? '', + env.POCKETBASE_INTERNAL_URL || env.PUBLIC_POCKETBASE_URL || 'http://localhost:8080' + ); + event.locals.user = event.locals.pb.authStore.record; + + const path = event.url.pathname; + const isAdminRoute = path.startsWith('/admin'); + const isLoginRoute = path === '/admin/login'; + const isAuthed = event.locals.pb.authStore.isValid; + + if (isAdminRoute && !isLoginRoute && !isAuthed) { + throw redirect(303, '/admin/login'); + } + + if (isLoginRoute && isAuthed) { + throw redirect(303, '/admin/pages'); + } + + const response = await resolve(event); + response.headers.append('set-cookie', event.locals.pb.authStore.exportToCookie({ sameSite: 'lax' }, 'pb_auth')); + return response; +}; diff --git a/app/src/lib/admin/BlockList.svelte b/app/src/lib/admin/BlockList.svelte index bbe1402..5542697 100644 --- a/app/src/lib/admin/BlockList.svelte +++ b/app/src/lib/admin/BlockList.svelte @@ -1,63 +1,63 @@ - - -
- {#each blocks as block, i (block.id)} -
onSelect(block.id)} - ondragstart={() => (dragIndex = i)} - ondragover={(e) => e.preventDefault()} - ondrop={() => { if (dragIndex !== null && dragIndex !== i) onMove(dragIndex, i); dragIndex = null; }} - > -
- ☰ -
{blockLabels[block.type as BlockType]}
- -
-
- {/each} -
+ + +
+ {#each blocks as block, i (block.id)} +
onSelect(block.id)} + ondragstart={() => (dragIndex = i)} + ondragover={(e) => e.preventDefault()} + ondrop={() => { if (dragIndex !== null && dragIndex !== i) onMove(dragIndex, i); dragIndex = null; }} + > +
+ ☰ +
{blockLabels[block.type as BlockType]}
+ +
+
+ {/each} +
diff --git a/app/src/lib/admin/blockDefaults.ts b/app/src/lib/admin/blockDefaults.ts index 510f1eb..007ae9d 100644 --- a/app/src/lib/admin/blockDefaults.ts +++ b/app/src/lib/admin/blockDefaults.ts @@ -1,69 +1,69 @@ -import { v4 as uuid } from 'uuid'; -import type { BlockType, ContentBlock } from '$lib/types'; - -export const blockLabels: Record = { - text: 'Text', - image_text: 'Image + Text', - timeline: 'Timeline', - hero: 'Hero', - button: 'Button', - spacer: 'Spacer', - testimonials: 'Testimonials', - upcoming_calendar: 'Upcoming Calendar' -}; - -export const blockTypes = Object.keys(blockLabels) as BlockType[]; - -export function createBlock(type: BlockType): ContentBlock { - const base = { id: uuid(), type, data: {} as Record }; - switch (type) { - case 'text': - base.data = { content: '

New text block

Add your copy here.

' }; - break; - case 'image_text': - base.data = { url: '', alt: '', content: '

Image and text

Add content here.

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

New text block

Add your copy here.

' }; + break; + case 'image_text': + base.data = { url: '', alt: '', content: '

Image and text

Add content here.

', imagePosition: 'left' }; + break; + case 'timeline': + base.data = { items: [{ title: 'Milestone', description: 'Describe this moment.' }] }; + break; + case 'hero': + base.data = { + heading: 'Holistic and Experiential Learning about Happiness', + subheading: 'Individual sessions, workshops and events in Oslo', + buttonLabel: 'BOOK NOW', + buttonUrl: '/book' + }; + break; + case 'button': + base.data = { + label: 'Learn More', + href: '/', + variant: 'primary', + size: 'md', + alignment: 'center' + }; + break; + case 'spacer': + base.data = { height: 64 }; + break; + case 'testimonials': + base.data = { + title: 'What They Say About Me', + items: [ + { text: 'Recently I started to experience incredible whole-body orgasms. And now I know how it works. My awareness around sexuality changed for good and I feel like a boss of my own life. What a joy to have this freedom of choice.', title: 'Anne' }, + { text: 'I never thought it was possible to sense so much pleasure in my body without intense stimulations I got used to. After the series of sessions, I could feel something like a trance state by receiving only a gentle touch. That was a totally new experience for me.', title: 'Espen' }, + { text: "Eva's sexual healing methods should be accessible to everyone. I am amazed by the depth and integrity of the message she conveys through her work. I was meeting Eva for healing my body and, as a result, I reconnected with my heart and soul too.", title: 'Marie' }, + { text: "It is hard to surprise me with any sexual activity since I had many exciting experiments in my life. But I always suspected that there might be something more I have not yet felt and tried. Thanks to Eva I realised how much power I've got. Under her guidance, I have learnt to maximise my orgasmic potential and consciously play with arousal. By the way, my wife is also happy that I became enthusiastic about new sexual practices.", title: 'Jan' } + ] + }; + break; + case 'upcoming_calendar': + base.data = { + title: 'Upcoming Events', + categories: [] + }; + break; + } + base.data._background = { type: 'none', color: '', attachment: 'scroll', overlay: false, overlayOpacity: 40 }; + return base; +} diff --git a/app/src/lib/admin/editors/BlockEditor.svelte b/app/src/lib/admin/editors/BlockEditor.svelte index c65f223..09457cd 100644 --- a/app/src/lib/admin/editors/BlockEditor.svelte +++ b/app/src/lib/admin/editors/BlockEditor.svelte @@ -1,294 +1,294 @@ - - -{#if !block} -
Select a block to edit.
-{:else} -
-

{blockLabels[block.type as BlockType]}

- - {#if block.type === 'text'} - updateData({ content })} /> - {:else if block.type === 'image_text'} - updateData(image)} /> -
- -
-
updateData({ content })} />
- {:else if block.type === 'timeline'} - {#each block.data.items || [] as item, i} -
- updateArray('items', i, { title: e.currentTarget.value })} /> - - -
- {/each} - - {:else if block.type === 'hero'} - - - - - {:else if block.type === 'button'} -
- - -
- updateData({ variant: v })} - /> -
-
- updateData({ alignment: v })} - formatLabel={titleCase} - /> -
-
- updateData({ size: v })} - formatLabel={(v) => String({ xs: 'Extra Small', sm: 'Small', md: 'Medium', lg: 'Large' }[String(v)] || v)} - /> -
-
-
- Color -
- updateData({ color: e.currentTarget.value })} /> - updateData({ color: e.currentTarget.value })} /> -
-
-
-
- {:else if block.type === 'spacer'} -
- -
- {:else if block.type === 'testimonials'} -
- - - {#each block.data.items || [] as item, i} -
- - updateArray('items', i, { title: e.currentTarget.value })} - /> - -
- {/each} - -
- {:else if block.type === 'upcoming_calendar'} -
- - -
-
-

Category filters

-

Choose categories to show in this block. Leave all unchecked to show every published event.

-
- {#if eventCategories?.length} -
- {#each eventCategories as category} - - {/each} -
- {:else} -

No event categories exist yet. Create events in the Calendar admin page first.

- {/if} -
-
- {/if} - -
- - -
- updateData({ _background: { ...(block.data._background || {}), type: v } })} - /> -
- - {#if block.data._background?.type === 'color'} -
- -
- {/if} - - {#if block.data._background?.type === 'image'} -
- updateData({ _background: { ...(block.data._background || {}), imageUrl: image.url, imageAlt: image.alt } })} /> - - updateData({ _background: { ...(block.data._background || {}), attachment: v } })} - /> - - updateData({ _background: { ...(block.data._background || {}), overlay: true, overlayOpacity: v } })} - formatLabel={(v) => `${v}%`} - /> -
- {/if} - -
- - updateData({ _foreground: { ...(block.data._foreground || {}), mode: v } })} - /> - - {#if block.data._foreground?.mode === 'custom'} -
-
-
- Heading -
- updateData({ _foreground: { ...(block.data._foreground || {}), headingColor: e.currentTarget.value } })} /> - updateData({ _foreground: { ...(block.data._foreground || {}), headingColor: e.currentTarget.value } })} /> -
-
-
-
-
- Sub heading -
- updateData({ _foreground: { ...(block.data._foreground || {}), subheadingColor: e.currentTarget.value } })} /> - updateData({ _foreground: { ...(block.data._foreground || {}), subheadingColor: e.currentTarget.value } })} /> -
-
-
-
-
- Text -
- updateData({ _foreground: { ...(block.data._foreground || {}), textColor: e.currentTarget.value } })} /> - updateData({ _foreground: { ...(block.data._foreground || {}), textColor: e.currentTarget.value } })} /> -
-
-
-
- {/if} -
-
-{/if} + + +{#if !block} +
Select a block to edit.
+{:else} +
+

{blockLabels[block.type as BlockType]}

+ + {#if block.type === 'text'} + updateData({ content })} /> + {:else if block.type === 'image_text'} + updateData(image)} /> +
+ +
+
updateData({ content })} />
+ {:else if block.type === 'timeline'} + {#each block.data.items || [] as item, i} +
+ updateArray('items', i, { title: e.currentTarget.value })} /> + + +
+ {/each} + + {:else if block.type === 'hero'} + + + + + {:else if block.type === 'button'} +
+ + +
+ updateData({ variant: v })} + /> +
+
+ updateData({ alignment: v })} + formatLabel={titleCase} + /> +
+
+ updateData({ size: v })} + formatLabel={(v) => String({ xs: 'Extra Small', sm: 'Small', md: 'Medium', lg: 'Large' }[String(v)] || v)} + /> +
+
+
+ Color +
+ updateData({ color: e.currentTarget.value })} /> + updateData({ color: e.currentTarget.value })} /> +
+
+
+
+ {:else if block.type === 'spacer'} +
+ +
+ {:else if block.type === 'testimonials'} +
+ + + {#each block.data.items || [] as item, i} +
+ + updateArray('items', i, { title: e.currentTarget.value })} + /> + +
+ {/each} + +
+ {:else if block.type === 'upcoming_calendar'} +
+ + +
+
+

Category filters

+

Choose categories to show in this block. Leave all unchecked to show every published event.

+
+ {#if eventCategories?.length} +
+ {#each eventCategories as category} + + {/each} +
+ {:else} +

No event categories exist yet. Create events in the Calendar admin page first.

+ {/if} +
+
+ {/if} + +
+ + +
+ updateData({ _background: { ...(block.data._background || {}), type: v } })} + /> +
+ + {#if block.data._background?.type === 'color'} +
+ +
+ {/if} + + {#if block.data._background?.type === 'image'} +
+ updateData({ _background: { ...(block.data._background || {}), imageUrl: image.url, imageAlt: image.alt } })} /> + + updateData({ _background: { ...(block.data._background || {}), attachment: v } })} + /> + + updateData({ _background: { ...(block.data._background || {}), overlay: true, overlayOpacity: v } })} + formatLabel={(v) => `${v}%`} + /> +
+ {/if} + +
+ + updateData({ _foreground: { ...(block.data._foreground || {}), mode: v } })} + /> + + {#if block.data._foreground?.mode === 'custom'} +
+
+
+ Heading +
+ updateData({ _foreground: { ...(block.data._foreground || {}), headingColor: e.currentTarget.value } })} /> + updateData({ _foreground: { ...(block.data._foreground || {}), headingColor: e.currentTarget.value } })} /> +
+
+
+
+
+ Sub heading +
+ updateData({ _foreground: { ...(block.data._foreground || {}), subheadingColor: e.currentTarget.value } })} /> + updateData({ _foreground: { ...(block.data._foreground || {}), subheadingColor: e.currentTarget.value } })} /> +
+
+
+
+
+ Text +
+ updateData({ _foreground: { ...(block.data._foreground || {}), textColor: e.currentTarget.value } })} /> + updateData({ _foreground: { ...(block.data._foreground || {}), textColor: e.currentTarget.value } })} /> +
+
+
+
+ {/if} +
+
+{/if} diff --git a/app/src/lib/admin/editors/ImageUploader.svelte b/app/src/lib/admin/editors/ImageUploader.svelte index 3eed305..bb09383 100644 --- a/app/src/lib/admin/editors/ImageUploader.svelte +++ b/app/src/lib/admin/editors/ImageUploader.svelte @@ -1,105 +1,105 @@ - - -
- -
fileInput?.click()} - onkeydown={(e) => e.key === 'Enter' && fileInput?.click()} - > - {#if uploading} - -

Uploading…

- {:else if localUrl} -
- {localAlt} - -
- {:else} - - - -

Upload image

-

PNG, JPG, WebP

- {/if} -
- - {#if error} -
{error}
- {/if} - - - - -
- - -
-
+ + +
+ +
fileInput?.click()} + onkeydown={(e) => e.key === 'Enter' && fileInput?.click()} + > + {#if uploading} + +

Uploading…

+ {:else if localUrl} +
+ {localAlt} + +
+ {:else} + + + +

Upload image

+

PNG, JPG, WebP

+ {/if} +
+ + {#if error} +
{error}
+ {/if} + + + + +
+ + +
+
diff --git a/app/src/lib/admin/editors/RichTextEditor.svelte b/app/src/lib/admin/editors/RichTextEditor.svelte index 569fa04..99b7f73 100644 --- a/app/src/lib/admin/editors/RichTextEditor.svelte +++ b/app/src/lib/admin/editors/RichTextEditor.svelte @@ -1,78 +1,78 @@ - - -{#if mounted} -
-
- - - - - - - -
-
{ if (e.key === 'Tab') { e.preventDefault(); exec('insertHTML', ' '); } }} - >
-
-{:else} -
Loading editor…
-{/if} + + +{#if mounted} +
+
+ + + + + + + +
+
{ if (e.key === 'Tab') { e.preventDefault(); exec('insertHTML', ' '); } }} + >
+
+{:else} +
Loading editor…
+{/if} diff --git a/app/src/lib/admin/editors/SegmentedControl.svelte b/app/src/lib/admin/editors/SegmentedControl.svelte index 0c6cd0a..0209a19 100644 --- a/app/src/lib/admin/editors/SegmentedControl.svelte +++ b/app/src/lib/admin/editors/SegmentedControl.svelte @@ -1,38 +1,38 @@ - - -
-
- {#if label} - {label} - {/if} -
- {#each options as option, i} - - {/each} -
-
+ + +
+
+ {#if label} + {label} + {/if} +
+ {#each options as option, i} + + {/each} +
+
\ No newline at end of file diff --git a/app/src/lib/blocks/BackgroundWrapper.svelte b/app/src/lib/blocks/BackgroundWrapper.svelte index 4012254..2dd149f 100644 --- a/app/src/lib/blocks/BackgroundWrapper.svelte +++ b/app/src/lib/blocks/BackgroundWrapper.svelte @@ -1,54 +1,54 @@ - - -
- {#if background.type === 'image' && background.overlay && background.imageUrl} -
- {/if} -
- {@render children()} -
-
+ + +
+ {#if background.type === 'image' && background.overlay && background.imageUrl} +
+ {/if} +
+ {@render children()} +
+
diff --git a/app/src/lib/blocks/BlockRenderer.svelte b/app/src/lib/blocks/BlockRenderer.svelte index c6e8cca..bd80f73 100644 --- a/app/src/lib/blocks/BlockRenderer.svelte +++ b/app/src/lib/blocks/BlockRenderer.svelte @@ -1,44 +1,44 @@ - - -{#each blocks as block (block.id)} - - {#if block.type === 'text'} - - {:else if block.type === 'image_text'} - - {:else if block.type === 'timeline'} - - {:else if block.type === 'hero'} - - {:else if block.type === 'button'} - - {:else if block.type === 'spacer'} - - {:else if block.type === 'testimonials'} - - {:else if block.type === 'upcoming_calendar'} - - {/if} - -{/each} + + +{#each blocks as block (block.id)} + + {#if block.type === 'text'} + + {:else if block.type === 'image_text'} + + {:else if block.type === 'timeline'} + + {:else if block.type === 'hero'} + + {:else if block.type === 'button'} + + {:else if block.type === 'spacer'} + + {:else if block.type === 'testimonials'} + + {:else if block.type === 'upcoming_calendar'} + + {/if} + +{/each} diff --git a/app/src/lib/blocks/ButtonBlock.svelte b/app/src/lib/blocks/ButtonBlock.svelte index d75a2f3..150457a 100644 --- a/app/src/lib/blocks/ButtonBlock.svelte +++ b/app/src/lib/blocks/ButtonBlock.svelte @@ -1,26 +1,26 @@ - - - + + + diff --git a/app/src/lib/blocks/HeroBlock.svelte b/app/src/lib/blocks/HeroBlock.svelte index 9e50164..c41b16f 100644 --- a/app/src/lib/blocks/HeroBlock.svelte +++ b/app/src/lib/blocks/HeroBlock.svelte @@ -1,30 +1,30 @@ - - -
-
-

- {data.heading || 'Holistic and Experiential Learning about Happiness'} -

- {#if data.subheading} -

- {data.subheading} -

- {/if} - {#if data.buttonLabel} - - {/if} -
-
+ + +
+
+

+ {data.heading || 'Holistic and Experiential Learning about Happiness'} +

+ {#if data.subheading} +

+ {data.subheading} +

+ {/if} + {#if data.buttonLabel} + + {/if} +
+
diff --git a/app/src/lib/blocks/ImageTextBlock.svelte b/app/src/lib/blocks/ImageTextBlock.svelte index da233e2..f59dfac 100644 --- a/app/src/lib/blocks/ImageTextBlock.svelte +++ b/app/src/lib/blocks/ImageTextBlock.svelte @@ -1,22 +1,22 @@ - - -
-
-
- {#if data.url} - {data.alt - {:else} -
Upload an image
- {/if} -
-
- {@html data.content || '

A gentler rhythm

Pair meaningful copy with a calming studio image.

'} -
-
-
+ + +
+
+
+ {#if data.url} + {data.alt + {:else} +
Upload an image
+ {/if} +
+
+ {@html data.content || '

A gentler rhythm

Pair meaningful copy with a calming studio image.

'} +
+
+
diff --git a/app/src/lib/blocks/SpacerBlock.svelte b/app/src/lib/blocks/SpacerBlock.svelte index bf93cde..39954e7 100644 --- a/app/src/lib/blocks/SpacerBlock.svelte +++ b/app/src/lib/blocks/SpacerBlock.svelte @@ -1,7 +1,7 @@ - - + +
\ No newline at end of file diff --git a/app/src/lib/blocks/TestimonialsBlock.svelte b/app/src/lib/blocks/TestimonialsBlock.svelte index 5704128..3347069 100644 --- a/app/src/lib/blocks/TestimonialsBlock.svelte +++ b/app/src/lib/blocks/TestimonialsBlock.svelte @@ -1,87 +1,87 @@ - - -
-
- -

- {title} -

- - -
- -
- {#each testimonials as testimonial, i} -
-

- "{testimonial.text}" -

-

- — {testimonial.title} -

-
- {/each} -
-
- - -
- - - -
- {#each testimonials as _, i} - - {/each} -
- - -
-
+ + +
+
+ +

+ {title} +

+ + +
+ +
+ {#each testimonials as testimonial, i} +
+

+ "{testimonial.text}" +

+

+ — {testimonial.title} +

+
+ {/each} +
+
+ + +
+ + + +
+ {#each testimonials as _, i} + + {/each} +
+ + +
+
\ No newline at end of file diff --git a/app/src/lib/blocks/TextBlock.svelte b/app/src/lib/blocks/TextBlock.svelte index 5abeecb..37ad0ce 100644 --- a/app/src/lib/blocks/TextBlock.svelte +++ b/app/src/lib/blocks/TextBlock.svelte @@ -1,11 +1,11 @@ - - -
-
- {@html data.content || '

Welcome

Add warm, inviting copy in the CMS.

'} -
-
+ + +
+
+ {@html data.content || '

Welcome

Add warm, inviting copy in the CMS.

'} +
+
diff --git a/app/src/lib/blocks/TimelineBlock.svelte b/app/src/lib/blocks/TimelineBlock.svelte index c81fd39..f73b2e7 100644 --- a/app/src/lib/blocks/TimelineBlock.svelte +++ b/app/src/lib/blocks/TimelineBlock.svelte @@ -1,31 +1,31 @@ - - -
-
-

Journey

-

A practice shaped over time

-
-
- {#each items as item, index} -
- -
-

{item.title}

-

{item.description}

-
-
- {/each} -
-
+ + +
+
+

Journey

+

A practice shaped over time

+
+
+ {#each items as item, index} +
+ +
+

{item.title}

+

{item.description}

+
+
+ {/each} +
+
diff --git a/app/src/lib/blocks/UpcomingCalendarBlock.svelte b/app/src/lib/blocks/UpcomingCalendarBlock.svelte index 92704b9..cfdb49a 100644 --- a/app/src/lib/blocks/UpcomingCalendarBlock.svelte +++ b/app/src/lib/blocks/UpcomingCalendarBlock.svelte @@ -1,126 +1,126 @@ - - -
-
-

Calendar

-

{data.title || 'Upcoming Events'}

-
- - {#if visibleEvents.length === 0} -
-

No upcoming events are available for the selected categories.

-
- {:else} -
- {#each months as month} -
-

{month.label}

-
- {#each weekdays as weekday}
{weekday}
{/each} -
-
- {#each month.days as day} -
-
- {day.dayNumber} -
-
- {#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} - - - {segment.showLabel ? event.name : '\u00a0'} - - - {:else} - - - {segment.showLabel ? event.name : '\u00a0'} - - - {/if} - {/each} -
-
- {/each} -
-
- {/each} -
- {/if} -
+ + +
+
+

Calendar

+

{data.title || 'Upcoming Events'}

+
+ + {#if visibleEvents.length === 0} +
+

No upcoming events are available for the selected categories.

+
+ {:else} +
+ {#each months as month} +
+

{month.label}

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

{footer.businessName}

-

{footer.tagline}

-
-
- {#if footer.address}

{footer.address}

{/if} - {#if footer.phone}

{footer.phone}

{/if} - {#if footer.email}

{footer.email}

{/if} -
-
- {#each footer.socialLinks || [] as link} - {#if link.url} - {link.platform} - {/if} - {/each} -
-
-
{footer.copyrightText}
-
+ + +
+
+
+

{footer.businessName}

+

{footer.tagline}

+
+
+ {#if footer.address}

{footer.address}

{/if} + {#if footer.phone}

{footer.phone}

{/if} + {#if footer.email}

{footer.email}

{/if} +
+
+ {#each footer.socialLinks || [] as link} + {#if link.url} + {link.platform} + {/if} + {/each} +
+
+
{footer.copyrightText}
+
diff --git a/app/src/lib/components/Header.svelte b/app/src/lib/components/Header.svelte index e94b917..5f8caaa 100644 --- a/app/src/lib/components/Header.svelte +++ b/app/src/lib/components/Header.svelte @@ -1,27 +1,27 @@ - - -
-
- - {#if header.logo?.url} - {header.logo.alt - {:else} - ES - {/if} - Eva Shafik - - - - - {#if header.ctaButton?.label} - {header.ctaButton.label} - {/if} -
-
+ + +
+
+ + {#if header.logo?.url} + {header.logo.alt + {:else} + ES + {/if} + Eva Shafik + + + + + {#if header.ctaButton?.label} + {header.ctaButton.label} + {/if} +
+
diff --git a/app/src/lib/exportImport.ts b/app/src/lib/exportImport.ts index 856d211..ff901d0 100644 --- a/app/src/lib/exportImport.ts +++ b/app/src/lib/exportImport.ts @@ -1,139 +1,139 @@ -import type { CalendarEventRecord, ContentBlock } from '$lib/types'; - -/** - * The portable export format. - * Images are stored as base64 data-URIs so the file is fully self-contained. - */ -export type SiteExport = { - version: 1; - exportedAt: string; - pages: { - slug: string; - title: string; - blocks: ContentBlock[]; - published: boolean; - }[]; - globals: { - key: string; - data: Record; - }[]; - events?: Omit[]; - /** Maps original PocketBase file URLs → base64 data-URI */ - images: Record; -}; - -/** Regex to match PocketBase file URLs */ -const PB_FILE_RE = /https?:\/\/[^/]+\/api\/files\/([^/]+)\/([^/]+)\/([^\s"')]+)/g; - -/** - * Extract all PocketBase image URLs from a value (recursive). - */ -export function extractImageUrls(value: unknown, urls = new Set()): Set { - if (typeof value === 'string') { - let match: RegExpExecArray | null; - const re = new RegExp(PB_FILE_RE.source, 'g'); - while ((match = re.exec(value)) !== null) { - urls.add(match[0]); - } - } else if (Array.isArray(value)) { - for (const item of value) extractImageUrls(item, urls); - } else if (value && typeof value === 'object') { - for (const v of Object.values(value as Record)) extractImageUrls(v, urls); - } - return urls; -} - -/** - * Replace all PocketBase URLs in a value with a placeholder key. - */ -export function replaceUrlsWithKeys( - value: unknown, - urlToKey: Map -): unknown { - if (typeof value === 'string') { - let result = value; - for (const [url, key] of urlToKey) { - result = result.replace(url, `__IMG__${key}__`); - } - return result; - } - if (Array.isArray(value)) { - return value.map((item) => replaceUrlsWithKeys(item, urlToKey)); - } - if (value && typeof value === 'object') { - const obj: Record = {}; - for (const [k, v] of Object.entries(value as Record)) { - obj[k] = replaceUrlsWithKeys(v, urlToKey); - } - return obj; - } - return value; -} - -/** - * Restore image placeholders back to real URLs after import. - */ -export function restorePlaceholders( - value: unknown, - keyToUrl: Map -): unknown { - if (typeof value === 'string') { - let result = value; - for (const [key, url] of keyToUrl) { - result = result.replace(`__IMG__${key}__`, url); - } - return result; - } - if (Array.isArray(value)) { - return value.map((item) => restorePlaceholders(item, keyToUrl)); - } - if (value && typeof value === 'object') { - const obj: Record = {}; - for (const [k, v] of Object.entries(value as Record)) { - obj[k] = restorePlaceholders(v, keyToUrl); - } - return obj; - } - return value; -} - -/** - * Generate a short unique key for an image URL. - */ -export function urlToKey(url: string): string { - const parts = url.split('/'); - const filename = parts[parts.length - 1] || 'img'; - const id = parts[parts.length - 2]?.slice(0, 8) || 'unknown'; - return `${id}_${filename}`; -} - -/** - * Fetch an image and return it as a base64 data-URI string. - */ -export async function fetchImageAsBase64(url: string): Promise { - const response = await fetch(url); - if (!response.ok) throw new Error(`Failed to fetch image: ${url} (${response.status})`); - const blob = await response.blob(); - const buffer = await blob.arrayBuffer(); - const bytes = new Uint8Array(buffer); - let binary = ''; - for (let i = 0; i < bytes.length; i++) { - binary += String.fromCharCode(bytes[i]); - } - const base64 = btoa(binary); - return `data:${blob.type};base64,${base64}`; -} - -/** - * Convert a base64 data-URI back to a File object for upload. - */ -export function dataUriToFile(dataUri: string, filename: string): File { - const [header, base64] = dataUri.split(','); - const mime = header.match(/data:(.*?);/)?.[1] || 'image/png'; - const binary = atob(base64); - const bytes = new Uint8Array(binary.length); - for (let i = 0; i < binary.length; i++) { - bytes[i] = binary.charCodeAt(i); - } - return new File([bytes], filename, { type: mime }); +import type { CalendarEventRecord, ContentBlock } from '$lib/types'; + +/** + * The portable export format. + * Images are stored as base64 data-URIs so the file is fully self-contained. + */ +export type SiteExport = { + version: 1; + exportedAt: string; + pages: { + slug: string; + title: string; + blocks: ContentBlock[]; + published: boolean; + }[]; + globals: { + key: string; + data: Record; + }[]; + events?: Omit[]; + /** Maps original PocketBase file URLs → base64 data-URI */ + images: Record; +}; + +/** Regex to match PocketBase file URLs */ +const PB_FILE_RE = /https?:\/\/[^/]+\/api\/files\/([^/]+)\/([^/]+)\/([^\s"')]+)/g; + +/** + * Extract all PocketBase image URLs from a value (recursive). + */ +export function extractImageUrls(value: unknown, urls = new Set()): Set { + if (typeof value === 'string') { + let match: RegExpExecArray | null; + const re = new RegExp(PB_FILE_RE.source, 'g'); + while ((match = re.exec(value)) !== null) { + urls.add(match[0]); + } + } else if (Array.isArray(value)) { + for (const item of value) extractImageUrls(item, urls); + } else if (value && typeof value === 'object') { + for (const v of Object.values(value as Record)) extractImageUrls(v, urls); + } + return urls; +} + +/** + * Replace all PocketBase URLs in a value with a placeholder key. + */ +export function replaceUrlsWithKeys( + value: unknown, + urlToKey: Map +): unknown { + if (typeof value === 'string') { + let result = value; + for (const [url, key] of urlToKey) { + result = result.replace(url, `__IMG__${key}__`); + } + return result; + } + if (Array.isArray(value)) { + return value.map((item) => replaceUrlsWithKeys(item, urlToKey)); + } + if (value && typeof value === 'object') { + const obj: Record = {}; + for (const [k, v] of Object.entries(value as Record)) { + obj[k] = replaceUrlsWithKeys(v, urlToKey); + } + return obj; + } + return value; +} + +/** + * Restore image placeholders back to real URLs after import. + */ +export function restorePlaceholders( + value: unknown, + keyToUrl: Map +): unknown { + if (typeof value === 'string') { + let result = value; + for (const [key, url] of keyToUrl) { + result = result.replace(`__IMG__${key}__`, url); + } + return result; + } + if (Array.isArray(value)) { + return value.map((item) => restorePlaceholders(item, keyToUrl)); + } + if (value && typeof value === 'object') { + const obj: Record = {}; + for (const [k, v] of Object.entries(value as Record)) { + obj[k] = restorePlaceholders(v, keyToUrl); + } + return obj; + } + return value; +} + +/** + * Generate a short unique key for an image URL. + */ +export function urlToKey(url: string): string { + const parts = url.split('/'); + const filename = parts[parts.length - 1] || 'img'; + const id = parts[parts.length - 2]?.slice(0, 8) || 'unknown'; + return `${id}_${filename}`; +} + +/** + * Fetch an image and return it as a base64 data-URI string. + */ +export async function fetchImageAsBase64(url: string): Promise { + const response = await fetch(url); + if (!response.ok) throw new Error(`Failed to fetch image: ${url} (${response.status})`); + const blob = await response.blob(); + const buffer = await blob.arrayBuffer(); + const bytes = new Uint8Array(buffer); + let binary = ''; + for (let i = 0; i < bytes.length; i++) { + binary += String.fromCharCode(bytes[i]); + } + const base64 = btoa(binary); + return `data:${blob.type};base64,${base64}`; +} + +/** + * Convert a base64 data-URI back to a File object for upload. + */ +export function dataUriToFile(dataUri: string, filename: string): File { + const [header, base64] = dataUri.split(','); + const mime = header.match(/data:(.*?);/)?.[1] || 'image/png'; + const binary = atob(base64); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) { + bytes[i] = binary.charCodeAt(i); + } + return new File([bytes], filename, { type: mime }); } \ No newline at end of file diff --git a/app/src/lib/pb.ts b/app/src/lib/pb.ts index dec3559..3979d69 100644 --- a/app/src/lib/pb.ts +++ b/app/src/lib/pb.ts @@ -1,37 +1,37 @@ -import PocketBase from 'pocketbase'; -import { env } from '$env/dynamic/public'; -import { browser } from '$app/environment'; - -export const pbUrl = env.PUBLIC_POCKETBASE_URL || 'http://localhost:8090'; - -export function createPocketBase(authCookie?: string, url = pbUrl) { - const pb = new PocketBase(url); - pb.autoCancellation(false); - - if (authCookie) { - pb.authStore.loadFromCookie(authCookie, 'pb_auth'); - } else if (browser) { - pb.authStore.loadFromCookie(document.cookie, 'pb_auth'); - } - - return pb; -} - -export const pb = createPocketBase(); - -export function getFileUrl(collectionIdOrName: string, recordId: string, filename: string) { - return `${pbUrl}/api/files/${collectionIdOrName}/${recordId}/${filename}`; -} - -export async function uploadMedia(file: File) { - const formData = new FormData(); - formData.append('file', file); - formData.append('alt', file.name.replace(/\.[^/.]+$/, '').replace(/[-_]/g, ' ')); - - const res = await fetch('/admin/api/upload', { method: 'POST', body: formData }); - if (!res.ok) { - const err = await res.json().catch(() => ({})); - throw new Error(err?.message || `Upload failed (${res.status})`); - } - return res.json(); -} +import PocketBase from 'pocketbase'; +import { env } from '$env/dynamic/public'; +import { browser } from '$app/environment'; + +export const pbUrl = env.PUBLIC_POCKETBASE_URL || 'http://localhost:8080'; + +export function createPocketBase(authCookie?: string, url = pbUrl) { + const pb = new PocketBase(url); + pb.autoCancellation(false); + + if (authCookie) { + pb.authStore.loadFromCookie(authCookie, 'pb_auth'); + } else if (browser) { + pb.authStore.loadFromCookie(document.cookie, 'pb_auth'); + } + + return pb; +} + +export const pb = createPocketBase(); + +export function getFileUrl(collectionIdOrName: string, recordId: string, filename: string) { + return `${pbUrl}/api/files/${collectionIdOrName}/${recordId}/${filename}`; +} + +export async function uploadMedia(file: File) { + const formData = new FormData(); + formData.append('file', file); + formData.append('alt', file.name.replace(/\.[^/.]+$/, '').replace(/[-_]/g, ' ')); + + const res = await fetch('/admin/api/upload', { method: 'POST', body: formData }); + if (!res.ok) { + const err = await res.json().catch(() => ({})); + throw new Error(err?.message || `Upload failed (${res.status})`); + } + return res.json(); +} diff --git a/app/src/lib/scrollReveal.ts b/app/src/lib/scrollReveal.ts index 731951c..c69cebc 100644 --- a/app/src/lib/scrollReveal.ts +++ b/app/src/lib/scrollReveal.ts @@ -1,30 +1,30 @@ -/** - * Scroll reveal Svelte action — applies a CSS class when the element enters the viewport. - * Usage:
...
- * The `reveal` class is hidden initially; `reveal-visible` is added on intersection. - */ - -export function scrollReveal(node: HTMLElement, delay: number = 0) { - const observer = new IntersectionObserver( - (entries) => { - for (const entry of entries) { - if (entry.isIntersecting) { - if (delay > 0) { - node.style.transitionDelay = `${delay}s`; - } - node.classList.add('reveal-visible'); - observer.unobserve(node); - } - } - }, - { threshold: 0.1, rootMargin: '0px 0px -40px 0px' } - ); - - observer.observe(node); - - return { - destroy() { - observer.disconnect(); - } - }; +/** + * Scroll reveal Svelte action — applies a CSS class when the element enters the viewport. + * Usage:
...
+ * 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(); + } + }; } \ No newline at end of file diff --git a/app/src/lib/types.ts b/app/src/lib/types.ts index cf27d70..efe9dc9 100644 --- a/app/src/lib/types.ts +++ b/app/src/lib/types.ts @@ -1,113 +1,113 @@ -export type BlockType = - | 'text' - | 'image_text' - | 'timeline' - | 'hero' - | 'button' - | 'spacer' - | 'testimonials' - | 'upcoming_calendar'; - -export type BlockBackground = { - type: 'none' | 'color' | 'image'; - color: string; - imageUrl: string; - attachment: 'scroll' | 'fixed'; - overlay: boolean; - overlayOpacity: number; // 0–100 -}; - -export type BlockForeground = { - mode: 'default' | 'custom'; - headingColor: string; - subheadingColor: string; - textColor: string; -}; - -export type ContentBlock = { - id: string; - type: BlockType; - data: Record; -}; - -export type PageRecord = { - id: string; - slug: string; - title: string; - blocks: ContentBlock[]; - published: boolean; -}; - -export type CalendarEventRecord = { - id: string; - name: string; - start: string; - end?: string; - description?: string; - color: string; - link?: string; - categories: string[]; - published: boolean; - allDay: boolean; -}; - -export type UpcomingCalendarBlockData = { - title?: string; - categories?: string[]; -}; - -export type HeaderGlobal = { - logo: { url: string; alt: string }; - navLinks: { label: string; href: string }[]; - ctaButton: { label: string; href: string }; - homePage: string; -}; - -export type FooterGlobal = { - businessName: string; - tagline: string; - address: string; - phone: string; - email: string; - socialLinks: { platform: string; url: string }[]; - copyrightText: string; -}; - -export const defaultHeader: HeaderGlobal = { - logo: { url: '', alt: 'Massage studio logo' }, - navLinks: [ - { label: 'Home', href: '/' }, - { label: 'About', href: '/about' }, - { label: 'Services', href: '/services' } - ], - ctaButton: { label: 'Book Now', href: '/book' }, - homePage: 'home' -}; - -export const defaultFooter: FooterGlobal = { - businessName: 'Eva Shafik Massage', - tagline: 'Warm, restorative massage therapy for everyday wellbeing.', - address: '', - phone: '', - email: '', - socialLinks: [{ platform: 'instagram', url: '' }], - copyrightText: `© ${new Date().getFullYear()} Eva Shafik Massage. All rights reserved.` -}; - -export type ColorsGlobal = { - background: string; - heading: string; - subheading: string; - text: string; - primary: string; - accent: string; -}; - -export const defaultColors: ColorsGlobal = { - background: '#faf8f5', - heading: '#2c2c2c', - subheading: '#4a4a4a', - text: '#2c2c2c', - primary: '#8a9a7b', - accent: '#c9825f' -}; +export type BlockType = + | 'text' + | 'image_text' + | 'timeline' + | 'hero' + | 'button' + | 'spacer' + | 'testimonials' + | 'upcoming_calendar'; + +export type BlockBackground = { + type: 'none' | 'color' | 'image'; + color: string; + imageUrl: string; + attachment: 'scroll' | 'fixed'; + overlay: boolean; + overlayOpacity: number; // 0–100 +}; + +export type BlockForeground = { + mode: 'default' | 'custom'; + headingColor: string; + subheadingColor: string; + textColor: string; +}; + +export type ContentBlock = { + id: string; + type: BlockType; + data: Record; +}; + +export type PageRecord = { + id: string; + slug: string; + title: string; + blocks: ContentBlock[]; + published: boolean; +}; + +export type CalendarEventRecord = { + id: string; + name: string; + start: string; + end?: string; + description?: string; + color: string; + link?: string; + categories: string[]; + published: boolean; + allDay: boolean; +}; + +export type UpcomingCalendarBlockData = { + title?: string; + categories?: string[]; +}; + +export type HeaderGlobal = { + logo: { url: string; alt: string }; + navLinks: { label: string; href: string }[]; + ctaButton: { label: string; href: string }; + homePage: string; +}; + +export type FooterGlobal = { + businessName: string; + tagline: string; + address: string; + phone: string; + email: string; + socialLinks: { platform: string; url: string }[]; + copyrightText: string; +}; + +export const defaultHeader: HeaderGlobal = { + logo: { url: '', alt: 'Massage studio logo' }, + navLinks: [ + { label: 'Home', href: '/' }, + { label: 'About', href: '/about' }, + { label: 'Services', href: '/services' } + ], + ctaButton: { label: 'Book Now', href: '/book' }, + homePage: 'home' +}; + +export const defaultFooter: FooterGlobal = { + businessName: 'Eva Shafik Massage', + tagline: 'Warm, restorative massage therapy for everyday wellbeing.', + address: '', + phone: '', + email: '', + socialLinks: [{ platform: 'instagram', url: '' }], + copyrightText: `© ${new Date().getFullYear()} Eva Shafik Massage. All rights reserved.` +}; + +export type ColorsGlobal = { + background: string; + heading: string; + subheading: string; + text: string; + primary: string; + accent: string; +}; + +export const defaultColors: ColorsGlobal = { + background: '#faf8f5', + heading: '#2c2c2c', + subheading: '#4a4a4a', + text: '#2c2c2c', + primary: '#8a9a7b', + accent: '#c9825f' +}; diff --git a/app/src/routes/+layout.server.ts b/app/src/routes/+layout.server.ts index d271aab..4bf3f43 100644 --- a/app/src/routes/+layout.server.ts +++ b/app/src/routes/+layout.server.ts @@ -1,23 +1,23 @@ -import { defaultColors, defaultFooter, defaultHeader } from '$lib/types'; -import type { LayoutServerLoad } from './$types'; - -async function getGlobal(pb: App.Locals['pb'], key: string, fallback: unknown) { - try { - const record = await pb.collection('globals').getFirstListItem(`key = "${key}"`); - return record.data || fallback; - } catch { - return fallback; - } -} - -export const load: LayoutServerLoad = async ({ locals, url }) => { - const [header, footer, colors] = await Promise.all([ - getGlobal(locals.pb, 'header', defaultHeader), - getGlobal(locals.pb, 'footer', defaultFooter), - getGlobal(locals.pb, 'colors', defaultColors) - ]); - - if (!header.homePage) header.homePage = defaultHeader.homePage; - - return { header, footer, colors, user: locals.user, url: { pathname: url.pathname } }; -}; +import { defaultColors, defaultFooter, defaultHeader } from '$lib/types'; +import type { LayoutServerLoad } from './$types'; + +async function getGlobal(pb: App.Locals['pb'], key: string, fallback: unknown) { + try { + const record = await pb.collection('globals').getFirstListItem(`key = "${key}"`); + return record.data || fallback; + } catch { + return fallback; + } +} + +export const load: LayoutServerLoad = async ({ locals, url }) => { + const [header, footer, colors] = await Promise.all([ + getGlobal(locals.pb, 'header', defaultHeader), + getGlobal(locals.pb, 'footer', defaultFooter), + getGlobal(locals.pb, 'colors', defaultColors) + ]); + + if (!header.homePage) header.homePage = defaultHeader.homePage; + + return { header, footer, colors, user: locals.user, url: { pathname: url.pathname } }; +}; diff --git a/app/src/routes/+layout.svelte b/app/src/routes/+layout.svelte index 3ae9057..75a35b0 100644 --- a/app/src/routes/+layout.svelte +++ b/app/src/routes/+layout.svelte @@ -1,35 +1,35 @@ - - - - - - - -{#if isAdmin} - {@render children()} -{:else} -
-
{@render children()}
-