Compare commits

..
Author SHA1 Message Date
ngqileandClaude Opus 5.5 dc5cfd1c54 docs: archive add-hero-full-width
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 09:46:57 +08:00
ngqile fae25c11a6 Merge pull request 'feat(pages): a hero can run full width with points and a form card heading' (#72) from add-hero-full-width into main
CI / build-and-publish (push) Failing after 0s
2026-12-04 01:46:44 +00:00
ngqileandClaude Opus 5.5 b55b8d2d86 feat(pages): a hero can run full width with points and a form card heading
A full-width hero spans the window with a larger serif headline and a lighter
left-to-right shade. It may list up to 6 points and give its form card a heading
and text. Full-width neighbours join with no gap. Custom HTML frames now shrink
to 20 px and re-report their height when the page asks, so a short top bar no
longer leaves a blank band.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 09:46:32 +08:00
ngqile dbb58e6e94 Merge pull request 'fix(pages): a short Custom HTML block shrinks to its content height' (#71) from fix-frame-content-height into main
CI / build-and-publish (push) Failing after 0s
2026-12-03 12:07:10 +00:00
ngqileandClaude Opus 5.5 3d89eb3118 fix(pages): a short Custom HTML block shrinks to its content height
scrollHeight inside the frame never drops below the frame's own 600 px start height,
so a top bar left a large blank gap. The frame script now reports the content box height.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-03 20:06:57 +08:00
ngqile e70051f912 Merge pull request 'docs: archive add-hero-signup-form' (#70) from archive-hero-signup-form into main
CI / build-and-publish (push) Failing after 0s
2026-12-03 11:46:05 +00:00
ngqileandClaude Opus 5.5 0073b41333 docs: archive add-hero-signup-form
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-03 19:45:55 +08:00
ngqile d4a2646786 Merge pull request 'feat(pages): a hero section can carry the sign-up form beside its text' (#69) from add-hero-signup-form into main
CI / build-and-publish (push) Failing after 0s
2026-12-03 11:45:48 +00:00
ngqileandClaude Opus 5.5 48896d1958 fix(pages): top-align the hero text beside a long form and clear the editor's image button
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-03 19:45:34 +08:00
ngqileandClaude Opus 5.5 417af36227 feat(pages): a hero section can carry the sign-up form beside its text
A HERO block may name an event. services-counter checks it belongs to the
page's company; mobile-api serves and accepts the form for it like a FORM
block; the portal shows the form in a card beside the hero text (below it on
phones), with the hero's own event picker, "No form" by default.

OpenSpec change: add-hero-signup-form.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-03 19:36:16 +08:00
ngqile 55ae666f01 Merge pull request 'docs: archive add-k8s-deployment' (#68) from archive-k8s-deployment into main
CI / build-and-publish (push) Failing after 0s
2026-12-03 11:07:44 +00:00
ngqileandClaude Opus 5.5 ff39d3f452 docs: archive add-k8s-deployment (task 6.2, the server-side dry run on the real cluster, stays open for the first apply)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-03 19:07:36 +08:00
ngqile c17d2f4bf3 Merge pull request 'feat(deploy): Kubernetes manifests, secret and release scripts, manifest check' (#67) from add-k8s-deployment into main
CI / build-and-publish (push) Failing after 0s
2026-12-03 11:07:21 +00:00
ngqileandClaude Opus 5.5 12babb9b88 fix(deploy): create the namespace before the first secrets; prove probe settings; keep the start order as fallback
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-03 19:07:05 +08:00
ngqileandClaude Opus 5.5 c7bc7a8dcb feat(deploy): Kubernetes manifests, secret and release scripts, and a manifest check
deploy/k8s holds a Kustomize base (a Deployment and Service for each of the ten
images, with the probes, settings and mounts from docs/deployment.md) and a prod
overlay that pins every image to one commit SHA and routes only the admin portal
and mobile-api's exact WhatsApp webhook path through Traefik with TLS.

Secrets never enter git: deploy/k8s/secrets.example holds placeholders, the filled
copy in deploy/k8s/secrets is ignored, and deploy/create-secrets.sh loads it
without printing a value. deploy/set-release.sh pins or rolls back the release.

deploy/check.sh (also a CI step) renders the overlay in one pinned container,
validates it with kubeconform and refuses public routes to internal services,
latest or untagged images, Secret data or literal secret env values, mixed SHAs
and a second or rolling service-counter; --release also refuses unfilled cluster
facts. --self-test proves each rule fires on its fixture.

OpenSpec change: add-k8s-deployment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-03 19:03:28 +08:00
ngqile a0da31f0da Merge pull request 'fix(pages): keep the section toolbar inside the section' (#66) from fix-section-toolbar-clip into main
CI / build-and-publish (push) Failing after 0s
2026-12-03 09:48:15 +00:00
ngqileandClaude Opus 5.5 e3d7b7ec4c fix(pages): keep the section toolbar inside the section so the canvas edge never clips it
The toolbar hung 20 px above the selected section, so it was cut off for the
first section and for any section scrolled to the top of the canvas. It now
sits inside the section's top-right corner, and the hero's image button moves
to the top-left so the two never overlap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-03 17:48:04 +08:00
ngqile be74080492 Merge pull request 'docs: archive add-page-visual-editor' (#65) from archive-page-visual-editor into main
CI / build-and-publish (push) Failing after 0s
2026-12-03 08:19:49 +00:00
ngqileandClaude Opus 5.5 c346f43f0e docs: archive add-page-visual-editor
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-03 16:19:40 +08:00
ngqile 7cd2972a70 Merge pull request 'feat(pages): on-page visual editor for landing pages' (#64) from add-page-visual-editor into main
CI / build-and-publish (push) Failing after 0s
2026-12-03 08:19:05 +00:00
ngqileandClaude Opus 5.5 d42e60d104 docs: add-page-visual-editor spec covers reveal, empty-field cues and Ctrl+Z focus
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-03 16:18:40 +08:00
ngqileandClaude Opus 5.5 7f43869444 docs: tick add-page-visual-editor live check
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-03 16:13:10 +08:00
ngqileandClaude Opus 5.5 5c216551fa fix(pages): bring an added, copied or moved section into view on the canvas
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-03 16:12:59 +08:00
ngqileandClaude Opus 5.5 68159086a9 fix(pages): empty rich text on the canvas gets room and a faded cue
A new Text section was a thin line under its Add section button, with nothing
to click or read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-03 16:12:59 +08:00
ngqileandClaude Opus 5.5 cd3c2e1987 fix(pages): Ctrl+Z undoes when focus fell out of the editor
A toolbar button removed with its section drops focus on the canvas body, and
a button that just went disabled drops it on the page body; neither reached the
editor's key handler. Listen on both documents as a fallback.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-03 15:57:53 +08:00
ngqileandClaude Opus 5.5 d977467182 docs: the on-page editor in the deployment guide
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-03 15:31:16 +08:00
ngqileandClaude Opus 5.5 5f2ddf90ba feat(pages): on-page editor with canvas, side panel, section tools, undo and refusals
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-03 15:31:03 +08:00
ngqileandClaude Opus 5.5 d31661fd3e feat(pages): selection, section actions, undo and refusal mapping in the page draft
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-03 15:23:38 +08:00
ngqileandClaude Opus 5.5 af1bab4afa feat(pages): edit rich text in place on the canvas; say why a link is refused
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-03 15:20:16 +08:00
ngqileandClaude Opus 5.5 54ceb7b631 feat(pages): page canvas and in-place editing of landing page text
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-03 15:15:32 +08:00
ngqileandClaude Opus 5.5 537ac65dc0 docs: tick add-page-visual-editor 1.4
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-03 15:03:49 +08:00
ngqileandClaude Opus 5.5 ede3da1cbe feat(pages): ask before an in-app link leaves unsaved page edits
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-03 15:01:16 +08:00
ngqileandClaude Opus 5.5 6b3498d123 test(pages): cover the canvas frame; record its unsandboxed frame in the proposal
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-03 15:01:16 +08:00
ngqileandClaude Opus 5.5 7e916b77b9 refactor(pages): move the page editor's state and actions into usePageDraft
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-03 14:46:05 +08:00
ngqileandClaude Opus 5.5 b768b66f6f test(security): allow-list the editor canvas frame by its constant blank document
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-03 14:46:05 +08:00
ngqileandClaude Opus 5.5 5f4f3bc1ee feat(pages): canvas frame spike passes; Custom HTML frames listen on their own window
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-03 14:36:17 +08:00
ngqileandClaude Opus 5.5 55d9535ef2 docs: OpenSpec change add-page-visual-editor
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-03 12:20:48 +08:00
ngqile a0691188ca Merge pull request 'docs: archive add-page-drafts-and-templates' (#63) from archive-page-drafts-and-templates into main
CI / build-and-publish (push) Failing after 0s
2026-12-03 04:09:05 +00:00
ngqileandClaude Opus 5.5 de40c60eb9 docs: archive add-page-drafts-and-templates
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-03 12:08:57 +08:00
ngqile 3b977fc277 Merge pull request 'feat(pages): drafts for published pages, starter templates and duplicate' (#62) from add-page-drafts-and-templates into main
CI / build-and-publish (push) Failing after 0s
2026-12-03 04:07:23 +00:00
114 changed files with 5656 additions and 550 deletions

No files matched your search

+7
View File
@@ -47,6 +47,13 @@ jobs:
- name: Checkout
uses: actions/checkout@v4
- name: Check the Kubernetes manifests
# Proves each manifest rule still fires, then checks the prod overlay (openspec spec cluster-deployment).
# Cluster-fact placeholders are allowed here; deploy/check.sh --release refuses them before a real apply.
run: |
sh deploy/check.sh --self-test
sh deploy/check.sh
- name: Build and test the services
run: |
mvn -T 1C -B -Dmaven.repo.local=/root/.m2/repository-co-lite verify \
+3
View File
@@ -20,3 +20,6 @@ solvway-admin-portal/.impeccable/
# Build output
target/
# Filled-in Kubernetes secrets (templates: deploy/k8s/secrets.example)
deploy/k8s/secrets/
@@ -0,0 +1,35 @@
# expect: replicas must be 1
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: admin-portal}
spec:
replicas: 1
strategy: {type: RollingUpdate}
selector: {matchLabels: {app: admin-portal}}
template:
metadata: {labels: {app: admin-portal}}
spec:
containers:
- name: admin-portal
image: gitea.containerverse.dev/solvway/co-lite-admin-portal:abc1234
env:
- name: JWT_TOKEN
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: service-counter}
spec:
replicas: 2
strategy: {type: Recreate}
selector: {matchLabels: {app: service-counter}}
template:
metadata: {labels: {app: service-counter}}
spec:
containers:
- name: service-counter
image: gitea.containerverse.dev/solvway/co-lite-service-counter:abc1234
env:
- name: JWT_TOKEN
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
@@ -0,0 +1,18 @@
# expect: strategy must be Recreate
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: service-counter}
spec:
replicas: 1
strategy: {type: RollingUpdate}
selector: {matchLabels: {app: service-counter}}
template:
metadata: {labels: {app: service-counter}}
spec:
containers:
- name: service-counter
image: gitea.containerverse.dev/solvway/co-lite-service-counter:abc1234
env:
- name: JWT_TOKEN
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
+18
View File
@@ -0,0 +1,18 @@
# expect: not 'latest'
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: admin-portal}
spec:
replicas: 1
strategy: {type: RollingUpdate}
selector: {matchLabels: {app: admin-portal}}
template:
metadata: {labels: {app: admin-portal}}
spec:
containers:
- name: admin-portal
image: gitea.containerverse.dev/solvway/co-lite-admin-portal:latest
env:
- name: JWT_TOKEN
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
@@ -0,0 +1,90 @@
# expect: env JWT_SECRET holds a literal value
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: admin-portal}
spec:
replicas: 1
strategy: {type: RollingUpdate}
selector: {matchLabels: {app: admin-portal}}
template:
metadata: {labels: {app: admin-portal}}
spec:
containers:
- name: admin-portal
image: gitea.containerverse.dev/solvway/co-lite-admin-portal:abc1234
env:
- name: JWT_TOKEN
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: mobile-api}
spec:
replicas: 1
strategy: {type: RollingUpdate}
selector: {matchLabels: {app: mobile-api}}
template:
metadata: {labels: {app: mobile-api}}
spec:
containers:
- name: mobile-api
image: gitea.containerverse.dev/solvway/co-lite-mobile-api:abc1234
env:
- name: JWT_TOKEN
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: service-counter}
spec:
replicas: 1
strategy: {type: Recreate}
selector: {matchLabels: {app: service-counter}}
template:
metadata: {labels: {app: service-counter}}
spec:
containers:
- name: service-counter
image: gitea.containerverse.dev/solvway/co-lite-service-counter:abc1234
env:
- name: JWT_TOKEN
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
---
apiVersion: traefik.io/v1alpha1
kind: IngressRoute
metadata: {name: admin-portal}
spec:
entryPoints: [websecure]
routes:
- match: Host(`co-lite.example`)
kind: Rule
services: [{name: admin-portal, port: 3000}]
---
apiVersion: traefik.io/v1alpha1
kind: IngressRoute
metadata: {name: whatsapp-webhook}
spec:
entryPoints: [websecure]
routes:
- match: Host(`co-lite.example`) && Path(`/api/public/whatsapp/webhook`)
kind: Rule
services: [{name: mobile-api, port: 80}]
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: service-log}
spec:
replicas: 1
strategy: {type: RollingUpdate}
selector: {matchLabels: {app: service-log}}
template:
metadata: {labels: {app: service-log}}
spec:
containers:
- name: service-log
image: gitea.containerverse.dev/solvway/co-lite-service-log:abc1234
env:
- {name: JWT_SECRET, value: x}
- name: JWT_TOKEN
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
+89
View File
@@ -0,0 +1,89 @@
# expect: different tags
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: admin-portal}
spec:
replicas: 1
strategy: {type: RollingUpdate}
selector: {matchLabels: {app: admin-portal}}
template:
metadata: {labels: {app: admin-portal}}
spec:
containers:
- name: admin-portal
image: gitea.containerverse.dev/solvway/co-lite-admin-portal:abc1234
env:
- name: JWT_TOKEN
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: mobile-api}
spec:
replicas: 1
strategy: {type: RollingUpdate}
selector: {matchLabels: {app: mobile-api}}
template:
metadata: {labels: {app: mobile-api}}
spec:
containers:
- name: mobile-api
image: gitea.containerverse.dev/solvway/co-lite-mobile-api:abc1234
env:
- name: JWT_TOKEN
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: service-counter}
spec:
replicas: 1
strategy: {type: Recreate}
selector: {matchLabels: {app: service-counter}}
template:
metadata: {labels: {app: service-counter}}
spec:
containers:
- name: service-counter
image: gitea.containerverse.dev/solvway/co-lite-service-counter:abc1234
env:
- name: JWT_TOKEN
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
---
apiVersion: traefik.io/v1alpha1
kind: IngressRoute
metadata: {name: admin-portal}
spec:
entryPoints: [websecure]
routes:
- match: Host(`co-lite.example`)
kind: Rule
services: [{name: admin-portal, port: 3000}]
---
apiVersion: traefik.io/v1alpha1
kind: IngressRoute
metadata: {name: whatsapp-webhook}
spec:
entryPoints: [websecure]
routes:
- match: Host(`co-lite.example`) && Path(`/api/public/whatsapp/webhook`)
kind: Rule
services: [{name: mobile-api, port: 80}]
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: service-log}
spec:
replicas: 1
strategy: {type: RollingUpdate}
selector: {matchLabels: {app: service-log}}
template:
metadata: {labels: {app: service-log}}
spec:
containers:
- name: service-log
image: gitea.containerverse.dev/solvway/co-lite-service-log:def5678
env:
- name: JWT_TOKEN
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
+77
View File
@@ -0,0 +1,77 @@
# expect: Service type NodePort
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: admin-portal}
spec:
replicas: 1
strategy: {type: RollingUpdate}
selector: {matchLabels: {app: admin-portal}}
template:
metadata: {labels: {app: admin-portal}}
spec:
containers:
- name: admin-portal
image: gitea.containerverse.dev/solvway/co-lite-admin-portal:abc1234
env:
- name: JWT_TOKEN
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: mobile-api}
spec:
replicas: 1
strategy: {type: RollingUpdate}
selector: {matchLabels: {app: mobile-api}}
template:
metadata: {labels: {app: mobile-api}}
spec:
containers:
- name: mobile-api
image: gitea.containerverse.dev/solvway/co-lite-mobile-api:abc1234
env:
- name: JWT_TOKEN
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: service-counter}
spec:
replicas: 1
strategy: {type: Recreate}
selector: {matchLabels: {app: service-counter}}
template:
metadata: {labels: {app: service-counter}}
spec:
containers:
- name: service-counter
image: gitea.containerverse.dev/solvway/co-lite-service-counter:abc1234
env:
- name: JWT_TOKEN
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
---
apiVersion: traefik.io/v1alpha1
kind: IngressRoute
metadata: {name: admin-portal}
spec:
entryPoints: [websecure]
routes:
- match: Host(`co-lite.example`)
kind: Rule
services: [{name: admin-portal, port: 3000}]
---
apiVersion: traefik.io/v1alpha1
kind: IngressRoute
metadata: {name: whatsapp-webhook}
spec:
entryPoints: [websecure]
routes:
- match: Host(`co-lite.example`) && Path(`/api/public/whatsapp/webhook`)
kind: Rule
services: [{name: mobile-api, port: 80}]
---
apiVersion: v1
kind: Service
metadata: {name: api-gateway}
spec: {type: NodePort, ports: [{port: 80}]}
+18
View File
@@ -0,0 +1,18 @@
# expect: not 'no tag'
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: admin-portal}
spec:
replicas: 1
strategy: {type: RollingUpdate}
selector: {matchLabels: {app: admin-portal}}
template:
metadata: {labels: {app: admin-portal}}
spec:
containers:
- name: admin-portal
image: gitea.containerverse.dev/solvway/co-lite-admin-portal
env:
- name: JWT_TOKEN
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
@@ -0,0 +1,78 @@
# expect: still a placeholder: <mysql host>
# flags: --release
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: admin-portal}
spec:
replicas: 1
strategy: {type: RollingUpdate}
selector: {matchLabels: {app: admin-portal}}
template:
metadata: {labels: {app: admin-portal}}
spec:
containers:
- name: admin-portal
image: gitea.containerverse.dev/solvway/co-lite-admin-portal:abc1234
env:
- name: JWT_TOKEN
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: mobile-api}
spec:
replicas: 1
strategy: {type: RollingUpdate}
selector: {matchLabels: {app: mobile-api}}
template:
metadata: {labels: {app: mobile-api}}
spec:
containers:
- name: mobile-api
image: gitea.containerverse.dev/solvway/co-lite-mobile-api:abc1234
env:
- name: JWT_TOKEN
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: service-counter}
spec:
replicas: 1
strategy: {type: Recreate}
selector: {matchLabels: {app: service-counter}}
template:
metadata: {labels: {app: service-counter}}
spec:
containers:
- name: service-counter
image: gitea.containerverse.dev/solvway/co-lite-service-counter:abc1234
env:
- name: JWT_TOKEN
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
---
apiVersion: traefik.io/v1alpha1
kind: IngressRoute
metadata: {name: admin-portal}
spec:
entryPoints: [websecure]
routes:
- match: Host(`co-lite.example`)
kind: Rule
services: [{name: admin-portal, port: 3000}]
---
apiVersion: traefik.io/v1alpha1
kind: IngressRoute
metadata: {name: whatsapp-webhook}
spec:
entryPoints: [websecure]
routes:
- match: Host(`co-lite.example`) && Path(`/api/public/whatsapp/webhook`)
kind: Rule
services: [{name: mobile-api, port: 80}]
---
apiVersion: v1
kind: ConfigMap
metadata: {name: co-lite-settings}
data: {MYSQLHOST: <mysql host>}
@@ -0,0 +1,82 @@
# expect: reaches 'api-gateway'
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: admin-portal}
spec:
replicas: 1
strategy: {type: RollingUpdate}
selector: {matchLabels: {app: admin-portal}}
template:
metadata: {labels: {app: admin-portal}}
spec:
containers:
- name: admin-portal
image: gitea.containerverse.dev/solvway/co-lite-admin-portal:abc1234
env:
- name: JWT_TOKEN
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: mobile-api}
spec:
replicas: 1
strategy: {type: RollingUpdate}
selector: {matchLabels: {app: mobile-api}}
template:
metadata: {labels: {app: mobile-api}}
spec:
containers:
- name: mobile-api
image: gitea.containerverse.dev/solvway/co-lite-mobile-api:abc1234
env:
- name: JWT_TOKEN
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: service-counter}
spec:
replicas: 1
strategy: {type: Recreate}
selector: {matchLabels: {app: service-counter}}
template:
metadata: {labels: {app: service-counter}}
spec:
containers:
- name: service-counter
image: gitea.containerverse.dev/solvway/co-lite-service-counter:abc1234
env:
- name: JWT_TOKEN
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
---
apiVersion: traefik.io/v1alpha1
kind: IngressRoute
metadata: {name: admin-portal}
spec:
entryPoints: [websecure]
routes:
- match: Host(`co-lite.example`)
kind: Rule
services: [{name: admin-portal, port: 3000}]
---
apiVersion: traefik.io/v1alpha1
kind: IngressRoute
metadata: {name: whatsapp-webhook}
spec:
entryPoints: [websecure]
routes:
- match: Host(`co-lite.example`) && Path(`/api/public/whatsapp/webhook`)
kind: Rule
services: [{name: mobile-api, port: 80}]
---
apiVersion: traefik.io/v1alpha1
kind: IngressRoute
metadata: {name: gw}
spec:
entryPoints: [websecure]
routes:
- match: Host(`co-lite.example`)
kind: Rule
services: [{name: api-gateway, port: 80}]
@@ -0,0 +1,82 @@
# expect: reaches 'mobile-api'
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: admin-portal}
spec:
replicas: 1
strategy: {type: RollingUpdate}
selector: {matchLabels: {app: admin-portal}}
template:
metadata: {labels: {app: admin-portal}}
spec:
containers:
- name: admin-portal
image: gitea.containerverse.dev/solvway/co-lite-admin-portal:abc1234
env:
- name: JWT_TOKEN
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: mobile-api}
spec:
replicas: 1
strategy: {type: RollingUpdate}
selector: {matchLabels: {app: mobile-api}}
template:
metadata: {labels: {app: mobile-api}}
spec:
containers:
- name: mobile-api
image: gitea.containerverse.dev/solvway/co-lite-mobile-api:abc1234
env:
- name: JWT_TOKEN
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: service-counter}
spec:
replicas: 1
strategy: {type: Recreate}
selector: {matchLabels: {app: service-counter}}
template:
metadata: {labels: {app: service-counter}}
spec:
containers:
- name: service-counter
image: gitea.containerverse.dev/solvway/co-lite-service-counter:abc1234
env:
- name: JWT_TOKEN
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
---
apiVersion: traefik.io/v1alpha1
kind: IngressRoute
metadata: {name: admin-portal}
spec:
entryPoints: [websecure]
routes:
- match: Host(`co-lite.example`)
kind: Rule
services: [{name: admin-portal, port: 3000}]
---
apiVersion: traefik.io/v1alpha1
kind: IngressRoute
metadata: {name: whatsapp-webhook}
spec:
entryPoints: [websecure]
routes:
- match: Host(`co-lite.example`) && Path(`/api/public/whatsapp/webhook`)
kind: Rule
services: [{name: mobile-api, port: 80}]
---
apiVersion: traefik.io/v1alpha1
kind: IngressRoute
metadata: {name: api}
spec:
entryPoints: [websecure]
routes:
- match: Host(`co-lite.example`) && PathPrefix(`/api/public/whatsapp/webhook`)
kind: Rule
services: [{name: mobile-api, port: 80}]
+77
View File
@@ -0,0 +1,77 @@
# expect: Secret with data
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: admin-portal}
spec:
replicas: 1
strategy: {type: RollingUpdate}
selector: {matchLabels: {app: admin-portal}}
template:
metadata: {labels: {app: admin-portal}}
spec:
containers:
- name: admin-portal
image: gitea.containerverse.dev/solvway/co-lite-admin-portal:abc1234
env:
- name: JWT_TOKEN
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: mobile-api}
spec:
replicas: 1
strategy: {type: RollingUpdate}
selector: {matchLabels: {app: mobile-api}}
template:
metadata: {labels: {app: mobile-api}}
spec:
containers:
- name: mobile-api
image: gitea.containerverse.dev/solvway/co-lite-mobile-api:abc1234
env:
- name: JWT_TOKEN
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: service-counter}
spec:
replicas: 1
strategy: {type: Recreate}
selector: {matchLabels: {app: service-counter}}
template:
metadata: {labels: {app: service-counter}}
spec:
containers:
- name: service-counter
image: gitea.containerverse.dev/solvway/co-lite-service-counter:abc1234
env:
- name: JWT_TOKEN
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
---
apiVersion: traefik.io/v1alpha1
kind: IngressRoute
metadata: {name: admin-portal}
spec:
entryPoints: [websecure]
routes:
- match: Host(`co-lite.example`)
kind: Rule
services: [{name: admin-portal, port: 3000}]
---
apiVersion: traefik.io/v1alpha1
kind: IngressRoute
metadata: {name: whatsapp-webhook}
spec:
entryPoints: [websecure]
routes:
- match: Host(`co-lite.example`) && Path(`/api/public/whatsapp/webhook`)
kind: Rule
services: [{name: mobile-api, port: 80}]
---
apiVersion: v1
kind: Secret
metadata: {name: co-lite-shared}
data: {JWT_TOKEN: eA==}
+72
View File
@@ -0,0 +1,72 @@
# expect: pass
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: admin-portal}
spec:
replicas: 1
strategy: {type: RollingUpdate}
selector: {matchLabels: {app: admin-portal}}
template:
metadata: {labels: {app: admin-portal}}
spec:
containers:
- name: admin-portal
image: gitea.containerverse.dev/solvway/co-lite-admin-portal:abc1234
env:
- name: JWT_TOKEN
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: mobile-api}
spec:
replicas: 1
strategy: {type: RollingUpdate}
selector: {matchLabels: {app: mobile-api}}
template:
metadata: {labels: {app: mobile-api}}
spec:
containers:
- name: mobile-api
image: gitea.containerverse.dev/solvway/co-lite-mobile-api:abc1234
env:
- name: JWT_TOKEN
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: service-counter}
spec:
replicas: 1
strategy: {type: Recreate}
selector: {matchLabels: {app: service-counter}}
template:
metadata: {labels: {app: service-counter}}
spec:
containers:
- name: service-counter
image: gitea.containerverse.dev/solvway/co-lite-service-counter:abc1234
env:
- name: JWT_TOKEN
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
---
apiVersion: traefik.io/v1alpha1
kind: IngressRoute
metadata: {name: admin-portal}
spec:
entryPoints: [websecure]
routes:
- match: Host(`co-lite.example`)
kind: Rule
services: [{name: admin-portal, port: 3000}]
---
apiVersion: traefik.io/v1alpha1
kind: IngressRoute
metadata: {name: whatsapp-webhook}
spec:
entryPoints: [websecure]
routes:
- match: Host(`co-lite.example`) && Path(`/api/public/whatsapp/webhook`)
kind: Rule
services: [{name: mobile-api, port: 80}]
+47
View File
@@ -0,0 +1,47 @@
#!/bin/sh
# Checks the production manifests (openspec spec cluster-deployment): renders deploy/k8s/overlays/prod, validates it
# against the Kubernetes schemas, then applies check_rules.py (public routes, pinned images, no secret data,
# one service-counter, all ten services present). Needs only Docker. The deploy folder goes to the container through stdin, so this also works
# against a remote Docker daemon (CI's DOCKER_HOST).
# deploy/check.sh check the prod overlay
# deploy/check.sh --self-test prove every rule fires on its fixture in deploy/check-fixtures
# deploy/check.sh --release also refuse any <…> placeholder; run it before every real apply
# deploy/check.sh --render print the rendered prod manifests
set -eu
IMAGE=alpine/k8s:1.33.4@sha256:b0523f0a244ddc4c8e055aa335c040d3d78b3ead5528f4544395f7f9f69c7b68
# Traefik's IngressRoute schema comes from the CRDs catalog; Kubernetes' own from kubeconform's default location.
CRDS='https://raw.githubusercontent.com/datreeio/CRDs-catalog/main/{{.Group}}/{{.ResourceKind}}_{{.ResourceAPIVersion}}.json'
cd "$(dirname "$0")/.."
in_container() {
tar -cf - deploy | docker run --rm -i "$IMAGE" sh -c "set -e; mkdir -p /w && tar -xf - -C /w && cd /w && $1"
}
case "${1:-}" in
--render)
in_container 'kubectl kustomize deploy/k8s/overlays/prod'
;;
--self-test)
in_container '
fail=0
for f in deploy/check-fixtures/*.yaml; do
expect=$(sed -n "1s/^# expect: //p" "$f")
flags=$(sed -n "2s/^# flags: //p" "$f")
if out=$(python3 -I deploy/check_rules.py $flags < "$f"); then got=pass; else got=$out; fi
case "$got" in
*"$expect"*) echo "ok $f" ;;
*) echo "FAIL $f: expected \"$expect\", got: $got"; fail=1 ;;
esac
done
exit $fail'
;;
""|--release)
in_container "
kubectl kustomize deploy/k8s/overlays/prod > /tmp/prod.yaml
kubeconform -strict -summary -schema-location default -schema-location '$CRDS' /tmp/prod.yaml
python3 -I deploy/check_rules.py --full ${1:-} < /tmp/prod.yaml && echo 'prod manifests: rules passed'"
;;
*)
echo "usage: $0 [--release|--self-test|--render]" >&2; exit 2
;;
esac
+127
View File
@@ -0,0 +1,127 @@
"""Production manifest rules (openspec spec cluster-deployment). Reads rendered multi-document YAML on stdin,
prints one line per violation and exits 1 if there is any. Runs inside the pinned alpine/k8s image (deploy/check.sh)."""
import re
import sys
import yaml
WEBHOOK = "/api/public/whatsapp/webhook"
PUBLIC = {"admin-portal"}
SECRETISH = re.compile(r"(SECRET|TOKEN|PASSWORD|PWD|KEY|KEYS)$")
WORKLOADS = {"Deployment", "StatefulSet", "DaemonSet", "Job", "CronJob"}
# The ten images of docs/deployment.md section 1; their Service names are fixed in the gateway's and mobile-api's config.
SYSTEM = {"admin-portal", "mobile-api", "api-gateway", "service-auth", "service-system", "service-counter",
"service-member", "service-log", "service-email", "service-whatsapp"}
def name(doc):
return f"{doc.get('kind')}/{(doc.get('metadata') or {}).get('name')}"
def pod_spec(doc):
spec = doc.get("spec") or {}
if doc.get("kind") == "CronJob":
spec = ((spec.get("jobTemplate") or {}).get("spec") or {})
return ((spec.get("template") or {}).get("spec") or {})
def check_route(doc, out):
for route in (doc.get("spec") or {}).get("routes") or []:
match = route.get("match", "")
for svc in route.get("services") or []:
target = svc.get("name")
if target in PUBLIC:
continue
exact = f"Path(`{WEBHOOK}`)" in match and "PathPrefix" not in match and "||" not in match
if target == "mobile-api" and exact:
continue
out.append(f"{name(doc)}: route '{match}' reaches '{target}'; only admin-portal and mobile-api's exact {WEBHOOK} may be public")
def check_images(doc, out):
spec = pod_spec(doc)
for c in (spec.get("containers") or []) + (spec.get("initContainers") or []):
image = c.get("image", "")
if "@sha256:" in image:
continue
last = image.rsplit("/", 1)[-1]
tag = last.split(":", 1)[1] if ":" in last else ""
if tag in ("", "latest"):
out.append(f"{name(doc)}: image '{image}' must be pinned to a commit SHA, not '{tag or 'no tag'}'")
elif "co-lite-" in last and not re.fullmatch(r"[0-9a-f]{7,40}", tag):
out.append(f"{name(doc)}: image '{image}' tag must be a commit SHA")
def check_env(doc, out):
spec = pod_spec(doc)
for c in (spec.get("containers") or []) + (spec.get("initContainers") or []):
for env in c.get("env") or []:
if SECRETISH.search(env.get("name", "")) and "value" in env:
out.append(f"{name(doc)}: env {env['name']} holds a literal value; take it from a Secret")
def complete(docs):
out = []
for kind in ("Deployment", "Service"):
have = {(d.get("metadata") or {}).get("name") for d in docs if d.get("kind") == kind}
out += [f"{kind}/{n}: missing from the manifests" for n in sorted(SYSTEM - have)]
return out
def placeholders(docs):
"""Before a real apply every <…> cluster fact must be filled in (deploy/check.sh --release)."""
out = []
def walk(doc, value, path):
if isinstance(value, dict):
for k, v in value.items():
walk(doc, v, f"{path}.{k}")
elif isinstance(value, list):
for i, v in enumerate(value):
walk(doc, v, f"{path}[{i}]")
elif isinstance(value, str) and re.search(r"<[^<>]+>", value):
out.append(f"{name(doc)}: {path.lstrip('.')} is still a placeholder: {value}")
for doc in docs:
walk(doc, doc, "")
return out
def rules(docs):
out = []
shas = {}
for doc in docs:
kind = doc.get("kind")
if kind == "Secret" and (doc.get("data") or doc.get("stringData")):
out.append(f"{name(doc)}: Secret with data in the manifests; create it with deploy/create-secrets.sh")
if kind in ("Ingress", "IngressRouteTCP", "IngressRouteUDP"):
out.append(f"{name(doc)}: {kind} is not allowed; public routes are Traefik IngressRoutes")
if kind == "Service" and (doc.get("spec") or {}).get("type", "ClusterIP") != "ClusterIP":
out.append(f"{name(doc)}: Service type {doc['spec']['type']} exposes it outside the cluster")
if kind == "IngressRoute":
check_route(doc, out)
if kind in WORKLOADS:
check_images(doc, out)
check_env(doc, out)
for c in pod_spec(doc).get("containers") or []:
last = c.get("image", "").rsplit("/", 1)[-1]
if last.startswith("co-lite-") and ":" in last:
shas.setdefault(last.split(":", 1)[1].split("@")[0], []).append(name(doc))
if kind == "Deployment" and doc["metadata"]["name"] == "service-counter":
spec = doc.get("spec") or {}
if spec.get("replicas", 1) != 1:
out.append(f"{name(doc)}: replicas must be 1 (the daily follow-up summary would be sent once per replica)")
if (spec.get("strategy") or {}).get("type") != "Recreate":
out.append(f"{name(doc)}: strategy must be Recreate so a rollout never runs two copies")
if len(shas) > 1:
out.append(f"images: co-lite images use different tags {sorted(shas)}; one release is one commit SHA")
return out
if __name__ == "__main__":
docs = [d for d in yaml.safe_load_all(sys.stdin) if d]
found = rules(docs) + (complete(docs) if "--full" in sys.argv else []) \
+ (placeholders(docs) if "--release" in sys.argv else [])
for line in found:
print(line)
sys.exit(1 if found else 0)
+74
View File
@@ -0,0 +1,74 @@
#!/bin/sh
# Creates or updates Co-Lite's Kubernetes Secrets from the filled-in copy of deploy/k8s/secrets.example
# (openspec spec cluster-deployment: secrets never enter the repository). Never prints a value.
# deploy/create-secrets.sh [--dry-run] [folder] folder defaults to deploy/k8s/secrets
# --dry-run checks the folder and lists the Secrets and key names without kubectl.
# NAMESPACE (default co-lite) picks the namespace.
set -eu
cd "$(dirname "$0")/.."
dry=
[ "${1:-}" = "--dry-run" ] && { dry=1; shift; }
src=${1:-deploy/k8s/secrets}
tpl=deploy/k8s/secrets.example
ns=${NAMESPACE:-co-lite}
optional="co-lite-whatsapp.env"
fail() { echo "create-secrets: $*" >&2; exit 1; }
[ -d "$src" ] || fail "no folder $src; copy $tpl there and fill it in"
keys() { sed -n 's/^\([A-Za-z_][A-Za-z0-9_]*\)=.*/\1/p' "$1"; }
value_of() { sed -n "s/^$2=//p" "$1" | head -n 1; }
# Check everything before creating anything, so a half-filled folder changes nothing.
for t in "$tpl"/*.env "$tpl"/*/; do
base=$(basename "$t")
f="$src/$base"
if [ ! -e "$f" ]; then
case " $optional " in *" $base "*) continue ;; esac
fail "missing $f"
fi
if [ -d "$t" ]; then
for k in "$t"*; do
kf="$f/$(basename "$k")"
[ -s "$kf" ] || fail "missing or empty $kf"
! grep -q '<[^<>]*>' "$kf" || fail "$kf still holds a <…> placeholder"
done
else
for k in $(keys "$t"); do
v=$(value_of "$f" "$k")
[ -n "$v" ] || fail "$f: $k is missing or empty"
case "$v" in *"<"*">"*) fail "$f: $k is still a placeholder" ;; esac
done
fi
done
apply() { # name, then kubectl create arguments
name=$1; shift
kubectl create secret "$@" "$name" -n "$ns" --dry-run=client -o yaml | kubectl apply -f - >/dev/null
echo "applied Secret $name"
}
if [ -z "$dry" ]; then
# The first run comes before the first apply, which is what would otherwise create the namespace.
kubectl create namespace "$ns" --dry-run=client -o yaml | kubectl apply -f - >/dev/null
fi
for f in "$src"/*.env "$src"/*/; do
[ -e "$f" ] || continue
name=$(basename "$f" .env); name=${name%/}
[ -e "$tpl/$(basename "$f")" ] || fail "$f has no template in $tpl"
if [ "$name" = co-lite-registry ]; then
echo "Secret $name (image pull secret for gitea.containerverse.dev)"
[ -n "$dry" ] && continue
tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT
auth=$(printf '%s:%s' "$(value_of "$f" REGISTRY_USER)" "$(value_of "$f" REGISTRY_PASSWORD)" | base64 | tr -d '\n')
(umask 077; printf '{"auths":{"gitea.containerverse.dev":{"auth":"%s"}}}' "$auth" > "$tmp/config.json")
apply "$name" generic --type=kubernetes.io/dockerconfigjson --from-file=.dockerconfigjson="$tmp/config.json"
elif [ -d "$f" ]; then
echo "Secret $name: $(ls "$f" | tr '\n' ' ')"
[ -n "$dry" ] && continue
apply "$name" generic --from-file="$f"
else
echo "Secret $name: $(keys "$f" | tr '\n' ' ')"
[ -n "$dry" ] && continue
apply "$name" generic --from-env-file="$f"
fi
done
+41
View File
@@ -0,0 +1,41 @@
# The only Service routed to as a whole (overlays/prod/routes.yaml). No health endpoint: GET /login answers 200 without a session.
apiVersion: apps/v1
kind: Deployment
metadata:
name: admin-portal
spec:
replicas: 1
selector:
matchLabels: {app: admin-portal}
template:
metadata:
labels: {app: admin-portal}
spec:
imagePullSecrets:
- {name: co-lite-registry}
containers:
- name: admin-portal
image: gitea.containerverse.dev/solvway/co-lite-admin-portal
ports:
- {name: http, containerPort: 3000}
envFrom:
- {configMapRef: {name: co-lite-portal}}
- {secretRef: {name: co-lite-admin-portal}}
livenessProbe:
tcpSocket: {port: http}
periodSeconds: 20
readinessProbe:
httpGet: {path: /login, port: http}
periodSeconds: 10
resources:
requests: {cpu: 100m, memory: 256Mi}
limits: {memory: 512Mi}
---
apiVersion: v1
kind: Service
metadata:
name: admin-portal
spec:
selector: {app: admin-portal}
ports:
- {name: http, port: 3000, targetPort: http}
+51
View File
@@ -0,0 +1,51 @@
# Routes to http://service-* on port 80; needs only JWT_TOKEN and the mounted appkeys.json (docs/deployment.md 6, 7).
apiVersion: apps/v1
kind: Deployment
metadata:
name: api-gateway
spec:
replicas: 1
selector:
matchLabels: {app: api-gateway}
template:
metadata:
labels: {app: api-gateway}
spec:
imagePullSecrets:
- {name: co-lite-registry}
containers:
- name: api-gateway
image: gitea.containerverse.dev/solvway/co-lite-api-gateway
ports:
- {name: http, containerPort: 80}
env:
- name: JWT_TOKEN
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
- name: JAVA_OPTS
valueFrom: {configMapKeyRef: {name: co-lite-settings, key: JAVA_OPTS}}
startupProbe:
httpGet: {path: /actuator/health/liveness, port: http}
periodSeconds: 10
failureThreshold: 30
livenessProbe:
httpGet: {path: /actuator/health/liveness, port: http}
periodSeconds: 20
readinessProbe:
httpGet: {path: /actuator/health/readiness, port: http}
periodSeconds: 10
resources:
requests: {cpu: 100m, memory: 512Mi}
limits: {memory: 1Gi}
volumeMounts:
- {name: appkeys, mountPath: /deployments/appkeys, readOnly: true}
volumes:
- {name: appkeys, secret: {secretName: co-lite-gateway-appkeys}}
---
apiVersion: v1
kind: Service
metadata:
name: api-gateway
spec:
selector: {app: api-gateway}
ports:
- {name: http, port: 80, targetPort: http}
+18
View File
@@ -0,0 +1,18 @@
# Co-Lite on Kubernetes: one Deployment and one Service per image (docs/deployment.md section 1).
# Settings and Secrets are referenced by name only; the prod overlay generates the settings and
# deploy/create-secrets.sh creates the Secrets. Images carry no tag here: the overlay pins one commit SHA.
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
labels:
- pairs: {app.kubernetes.io/part-of: co-lite}
resources:
- admin-portal.yaml
- api-gateway.yaml
- mobile-api.yaml
- service-auth.yaml
- service-counter.yaml
- service-email.yaml
- service-log.yaml
- service-member.yaml
- service-system.yaml
- service-whatsapp.yaml
+53
View File
@@ -0,0 +1,53 @@
# Internal; only its WhatsApp webhook path is public (overlays/prod/routes.yaml).
apiVersion: apps/v1
kind: Deployment
metadata:
name: mobile-api
spec:
replicas: 1
selector:
matchLabels: {app: mobile-api}
template:
metadata:
labels: {app: mobile-api}
spec:
imagePullSecrets:
- {name: co-lite-registry}
containers:
- name: mobile-api
image: gitea.containerverse.dev/solvway/co-lite-mobile-api
ports:
- {name: http, containerPort: 80}
envFrom:
- {configMapRef: {name: co-lite-settings}}
- {secretRef: {name: co-lite-shared}}
- {configMapRef: {name: co-lite-gcp}}
- {secretRef: {name: co-lite-mobile-api}}
- {configMapRef: {name: co-lite-whatsapp}}
- {secretRef: {name: co-lite-whatsapp, optional: true}}
startupProbe:
httpGet: {path: /actuator/health/liveness, port: http}
periodSeconds: 10
failureThreshold: 30
livenessProbe:
httpGet: {path: /actuator/health/liveness, port: http}
periodSeconds: 20
readinessProbe:
httpGet: {path: /actuator/health/readiness, port: http}
periodSeconds: 10
resources:
requests: {cpu: 100m, memory: 512Mi}
limits: {memory: 1Gi}
volumeMounts:
- {name: gcp-key, mountPath: /var/secrets/gcp, readOnly: true}
volumes:
- {name: gcp-key, secret: {secretName: co-lite-gcp-key}}
---
apiVersion: v1
kind: Service
metadata:
name: mobile-api
spec:
selector: {app: mobile-api}
ports:
- {name: http, port: 80, targetPort: http}
+50
View File
@@ -0,0 +1,50 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: service-auth
spec:
replicas: 1
selector:
matchLabels: {app: service-auth}
template:
metadata:
labels: {app: service-auth}
spec:
imagePullSecrets:
- {name: co-lite-registry}
containers:
- name: service-auth
image: gitea.containerverse.dev/solvway/co-lite-service-auth
ports:
- {name: http, containerPort: 80}
envFrom:
- {configMapRef: {name: co-lite-settings}}
- {secretRef: {name: co-lite-shared}}
- {configMapRef: {name: co-lite-gcp}}
- {secretRef: {name: co-lite-service-auth}}
startupProbe:
httpGet: {path: /actuator/health/liveness, port: http}
periodSeconds: 10
failureThreshold: 30
livenessProbe:
httpGet: {path: /actuator/health/liveness, port: http}
periodSeconds: 20
readinessProbe:
httpGet: {path: /actuator/health/readiness, port: http}
periodSeconds: 10
resources:
requests: {cpu: 100m, memory: 512Mi}
limits: {memory: 1Gi}
volumeMounts:
- {name: gcp-key, mountPath: /var/secrets/gcp, readOnly: true}
volumes:
- {name: gcp-key, secret: {secretName: co-lite-gcp-key}}
---
apiVersion: v1
kind: Service
metadata:
name: service-auth
spec:
selector: {app: service-auth}
ports:
- {name: http, port: 80, targetPort: http}
+51
View File
@@ -0,0 +1,51 @@
# Exactly one replica, replaced not rolled: it sends the daily follow-up summary (deploy/check_rules.py).
apiVersion: apps/v1
kind: Deployment
metadata:
name: service-counter
spec:
replicas: 1
strategy: {type: Recreate}
selector:
matchLabels: {app: service-counter}
template:
metadata:
labels: {app: service-counter}
spec:
imagePullSecrets:
- {name: co-lite-registry}
containers:
- name: service-counter
image: gitea.containerverse.dev/solvway/co-lite-service-counter
ports:
- {name: http, containerPort: 80}
envFrom:
- {configMapRef: {name: co-lite-settings}}
- {secretRef: {name: co-lite-shared}}
- {configMapRef: {name: co-lite-gcp}}
startupProbe:
httpGet: {path: /actuator/health/liveness, port: http}
periodSeconds: 10
failureThreshold: 30
livenessProbe:
httpGet: {path: /actuator/health/liveness, port: http}
periodSeconds: 20
readinessProbe:
httpGet: {path: /actuator/health/readiness, port: http}
periodSeconds: 10
resources:
requests: {cpu: 100m, memory: 768Mi}
limits: {memory: 1Gi}
volumeMounts:
- {name: gcp-key, mountPath: /var/secrets/gcp, readOnly: true}
volumes:
- {name: gcp-key, secret: {secretName: co-lite-gcp-key}}
---
apiVersion: v1
kind: Service
metadata:
name: service-counter
spec:
selector: {app: service-counter}
ports:
- {name: http, port: 80, targetPort: http}
+49
View File
@@ -0,0 +1,49 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: service-email
spec:
replicas: 1
selector:
matchLabels: {app: service-email}
template:
metadata:
labels: {app: service-email}
spec:
imagePullSecrets:
- {name: co-lite-registry}
containers:
- name: service-email
image: gitea.containerverse.dev/solvway/co-lite-service-email
ports:
- {name: http, containerPort: 80}
envFrom:
- {configMapRef: {name: co-lite-settings}}
- {secretRef: {name: co-lite-shared}}
- {configMapRef: {name: co-lite-gcp}}
startupProbe:
httpGet: {path: /actuator/health/liveness, port: http}
periodSeconds: 10
failureThreshold: 30
livenessProbe:
httpGet: {path: /actuator/health/liveness, port: http}
periodSeconds: 20
readinessProbe:
httpGet: {path: /actuator/health/readiness, port: http}
periodSeconds: 10
resources:
requests: {cpu: 100m, memory: 512Mi}
limits: {memory: 1Gi}
volumeMounts:
- {name: gcp-key, mountPath: /var/secrets/gcp, readOnly: true}
volumes:
- {name: gcp-key, secret: {secretName: co-lite-gcp-key}}
---
apiVersion: v1
kind: Service
metadata:
name: service-email
spec:
selector: {app: service-email}
ports:
- {name: http, port: 80, targetPort: http}
+49
View File
@@ -0,0 +1,49 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: service-log
spec:
replicas: 1
selector:
matchLabels: {app: service-log}
template:
metadata:
labels: {app: service-log}
spec:
imagePullSecrets:
- {name: co-lite-registry}
containers:
- name: service-log
image: gitea.containerverse.dev/solvway/co-lite-service-log
ports:
- {name: http, containerPort: 80}
envFrom:
- {configMapRef: {name: co-lite-settings}}
- {secretRef: {name: co-lite-shared}}
- {configMapRef: {name: co-lite-gcp}}
startupProbe:
httpGet: {path: /actuator/health/liveness, port: http}
periodSeconds: 10
failureThreshold: 30
livenessProbe:
httpGet: {path: /actuator/health/liveness, port: http}
periodSeconds: 20
readinessProbe:
httpGet: {path: /actuator/health/readiness, port: http}
periodSeconds: 10
resources:
requests: {cpu: 100m, memory: 512Mi}
limits: {memory: 1Gi}
volumeMounts:
- {name: gcp-key, mountPath: /var/secrets/gcp, readOnly: true}
volumes:
- {name: gcp-key, secret: {secretName: co-lite-gcp-key}}
---
apiVersion: v1
kind: Service
metadata:
name: service-log
spec:
selector: {app: service-log}
ports:
- {name: http, port: 80, targetPort: http}
+49
View File
@@ -0,0 +1,49 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: service-member
spec:
replicas: 1
selector:
matchLabels: {app: service-member}
template:
metadata:
labels: {app: service-member}
spec:
imagePullSecrets:
- {name: co-lite-registry}
containers:
- name: service-member
image: gitea.containerverse.dev/solvway/co-lite-service-member
ports:
- {name: http, containerPort: 80}
envFrom:
- {configMapRef: {name: co-lite-settings}}
- {secretRef: {name: co-lite-shared}}
- {configMapRef: {name: co-lite-gcp}}
startupProbe:
httpGet: {path: /actuator/health/liveness, port: http}
periodSeconds: 10
failureThreshold: 30
livenessProbe:
httpGet: {path: /actuator/health/liveness, port: http}
periodSeconds: 20
readinessProbe:
httpGet: {path: /actuator/health/readiness, port: http}
periodSeconds: 10
resources:
requests: {cpu: 100m, memory: 512Mi}
limits: {memory: 1Gi}
volumeMounts:
- {name: gcp-key, mountPath: /var/secrets/gcp, readOnly: true}
volumes:
- {name: gcp-key, secret: {secretName: co-lite-gcp-key}}
---
apiVersion: v1
kind: Service
metadata:
name: service-member
spec:
selector: {app: service-member}
ports:
- {name: http, port: 80, targetPort: http}
+49
View File
@@ -0,0 +1,49 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: service-system
spec:
replicas: 1
selector:
matchLabels: {app: service-system}
template:
metadata:
labels: {app: service-system}
spec:
imagePullSecrets:
- {name: co-lite-registry}
containers:
- name: service-system
image: gitea.containerverse.dev/solvway/co-lite-service-system
ports:
- {name: http, containerPort: 80}
envFrom:
- {configMapRef: {name: co-lite-settings}}
- {secretRef: {name: co-lite-shared}}
- {configMapRef: {name: co-lite-gcp}}
startupProbe:
httpGet: {path: /actuator/health/liveness, port: http}
periodSeconds: 10
failureThreshold: 30
livenessProbe:
httpGet: {path: /actuator/health/liveness, port: http}
periodSeconds: 20
readinessProbe:
httpGet: {path: /actuator/health/readiness, port: http}
periodSeconds: 10
resources:
requests: {cpu: 100m, memory: 512Mi}
limits: {memory: 1Gi}
volumeMounts:
- {name: gcp-key, mountPath: /var/secrets/gcp, readOnly: true}
volumes:
- {name: gcp-key, secret: {secretName: co-lite-gcp-key}}
---
apiVersion: v1
kind: Service
metadata:
name: service-system
spec:
selector: {app: service-system}
ports:
- {name: http, port: 80, targetPort: http}
+47
View File
@@ -0,0 +1,47 @@
# No Pub/Sub, Redis or key.json; reads the WhatsApp settings at startup.
apiVersion: apps/v1
kind: Deployment
metadata:
name: service-whatsapp
spec:
replicas: 1
selector:
matchLabels: {app: service-whatsapp}
template:
metadata:
labels: {app: service-whatsapp}
spec:
imagePullSecrets:
- {name: co-lite-registry}
containers:
- name: service-whatsapp
image: gitea.containerverse.dev/solvway/co-lite-service-whatsapp
ports:
- {name: http, containerPort: 80}
envFrom:
- {configMapRef: {name: co-lite-settings}}
- {secretRef: {name: co-lite-shared}}
- {configMapRef: {name: co-lite-whatsapp}}
- {secretRef: {name: co-lite-whatsapp, optional: true}}
startupProbe:
httpGet: {path: /actuator/health/liveness, port: http}
periodSeconds: 10
failureThreshold: 30
livenessProbe:
httpGet: {path: /actuator/health/liveness, port: http}
periodSeconds: 20
readinessProbe:
httpGet: {path: /actuator/health/readiness, port: http}
periodSeconds: 10
resources:
requests: {cpu: 100m, memory: 512Mi}
limits: {memory: 1Gi}
---
apiVersion: v1
kind: Service
metadata:
name: service-whatsapp
spec:
selector: {app: service-whatsapp}
ports:
- {name: http, port: 80, targetPort: http}
+3
View File
@@ -0,0 +1,3 @@
# Pub/Sub (docs/deployment.md section 5). The key itself is the co-lite-gcp-key Secret, mounted at /var/secrets/gcp.
GCP_PROJECT=<google cloud project id>
GCP_CREDENTIAL_FILE=file:/var/secrets/gcp/key.json
@@ -0,0 +1,43 @@
# Production: the team's cluster. Apply with `kubectl apply -k deploy/k8s/overlays/prod` after
# deploy/create-secrets.sh and deploy/check.sh --release (docs/deployment.md section 2).
# Every <…> value is a cluster fact still to be filled in; deploy/check.sh --release refuses them.
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: co-lite
resources:
- namespace.yaml
- ../../base
- routes.yaml
# Plain settings (docs/deployment.md section 6). Secrets are not here: deploy/create-secrets.sh makes them.
# A changed value gets a new ConfigMap name, so the pods that read it restart on the next apply.
configMapGenerator:
- name: co-lite-settings
envs: [settings.env]
- name: co-lite-gcp
envs: [gcp.env]
- name: co-lite-whatsapp
envs: [whatsapp.env]
- name: co-lite-portal
envs: [portal.env]
# One release is one commit SHA on main; change it with deploy/set-release.sh <sha>, roll back the same way.
images:
- name: gitea.containerverse.dev/solvway/co-lite-admin-portal
newTag: "a0da31f0da71bb8b4276774c6a79dcdd672cac2b"
- name: gitea.containerverse.dev/solvway/co-lite-api-gateway
newTag: "a0da31f0da71bb8b4276774c6a79dcdd672cac2b"
- name: gitea.containerverse.dev/solvway/co-lite-mobile-api
newTag: "a0da31f0da71bb8b4276774c6a79dcdd672cac2b"
- name: gitea.containerverse.dev/solvway/co-lite-service-auth
newTag: "a0da31f0da71bb8b4276774c6a79dcdd672cac2b"
- name: gitea.containerverse.dev/solvway/co-lite-service-counter
newTag: "a0da31f0da71bb8b4276774c6a79dcdd672cac2b"
- name: gitea.containerverse.dev/solvway/co-lite-service-email
newTag: "a0da31f0da71bb8b4276774c6a79dcdd672cac2b"
- name: gitea.containerverse.dev/solvway/co-lite-service-log
newTag: "a0da31f0da71bb8b4276774c6a79dcdd672cac2b"
- name: gitea.containerverse.dev/solvway/co-lite-service-member
newTag: "a0da31f0da71bb8b4276774c6a79dcdd672cac2b"
- name: gitea.containerverse.dev/solvway/co-lite-service-system
newTag: "a0da31f0da71bb8b4276774c6a79dcdd672cac2b"
- name: gitea.containerverse.dev/solvway/co-lite-service-whatsapp
newTag: "a0da31f0da71bb8b4276774c6a79dcdd672cac2b"
+4
View File
@@ -0,0 +1,4 @@
apiVersion: v1
kind: Namespace
metadata:
name: co-lite
+1
View File
@@ -0,0 +1 @@
MOBILE_API_BASE_URL=http://mobile-api
+31
View File
@@ -0,0 +1,31 @@
# The only public entry points (openspec spec cluster-deployment; deploy/check_rules.py enforces them):
# the admin portal, and exactly mobile-api's WhatsApp webhook path. Never route api-gateway or a service-*.
apiVersion: traefik.io/v1alpha1
kind: IngressRoute
metadata:
name: admin-portal
spec:
entryPoints: [websecure]
routes:
- match: Host(`co-lite.containerverse.dev`)
kind: Rule
services:
- name: admin-portal
port: 3000
tls:
certResolver: <traefik cert resolver>
---
apiVersion: traefik.io/v1alpha1
kind: IngressRoute
metadata:
name: whatsapp-webhook
spec:
entryPoints: [websecure]
routes:
- match: Host(`co-lite.containerverse.dev`) && Path(`/api/public/whatsapp/webhook`)
kind: Rule
services:
- name: mobile-api
port: 80
tls:
certResolver: <traefik cert resolver>
+9
View File
@@ -0,0 +1,9 @@
# Read by every Java service except api-gateway (which takes only JAVA_OPTS from here).
MYSQLHOST=<mysql host from the DBA>
MYSQLPORT=3306
REDISHOST=<host of the existing Redis>
APIGATEWAYURL=http://api-gateway
ADMIN_PORTAL_BASE_URL=https://co-lite.containerverse.dev
JAVA_OPTS=-Xmx384m
# mobile-api does not switch its liveness and readiness endpoints on by itself.
MANAGEMENT_HEALTH_PROBES_ENABLED=true
+7
View File
@@ -0,0 +1,7 @@
# WhatsApp stays off until WHATSAPP_COMPANIES is set (docs/deployment.md sections 6 and 11).
# To switch it on, uncomment and fill in; the tokens and app secrets go in the co-lite-whatsapp Secret.
# WHATSAPP_COMPANIES=INS,CV
# WHATSAPP_INS_PHONE_NUMBER_ID=
# WHATSAPP_INS_WABA_ID=
# WHATSAPP_CV_PHONE_NUMBER_ID=
# WHATSAPP_CV_WABA_ID=
+11
View File
@@ -0,0 +1,11 @@
# Secret templates
Placeholders only. Copy this folder to `deploy/k8s/secrets/` (git ignores it), fill in every `<…>`, then run
`deploy/create-secrets.sh`. Never commit the filled-in copy.
- `<name>.env` becomes the Secret `<name>`, one key per line.
- `<name>/` becomes the Secret `<name>`, one key per file (the file name is the key).
- `co-lite-registry.env` becomes the image pull secret for `gitea.containerverse.dev`.
- `co-lite-whatsapp.env` is optional: leave it out of `secrets/` while WhatsApp is off.
Make each random value separately, for example with `openssl rand -base64 48`. What each value is: `docs/deployment.md` sections 6 and 7.
@@ -0,0 +1,2 @@
MOBILE_API_KEY=<the portal key from AUTH_API_KEYS, without :APP>
SESSION_SECRET=<random, at least 32 characters>
@@ -0,0 +1,10 @@
[
{
"key": "<the APIKEY value given to mobile-api>",
"name": "Co-Lite mobile-api",
"desc": "mobile-api calls to the gateway",
"type": "BO",
"allowList": ["/"],
"ipList": ["<pod CIDR of the cluster>"]
}
]
@@ -0,0 +1 @@
<the Pub/Sub service-account JSON key file, docs/deployment.md section 5>
@@ -0,0 +1,4 @@
# APIKEY: the key in appkeys.json. AUTH_API_KEYS: <key>:APP entries, comma-separated; one is the portal's MOBILE_API_KEY.
APIKEY=<random, the same as the key in co-lite-gateway-appkeys/appkeys.json>
AUTH_API_KEYS=<portal key>:APP
JWT_SECRET=<the same value as JWT_TOKEN>
@@ -0,0 +1,3 @@
# A read-only package token for gitea.containerverse.dev, so the cluster can pull the images.
REGISTRY_USER=<gitea user>
REGISTRY_PASSWORD=<read-only package token>
@@ -0,0 +1,2 @@
AES_SECRET_KEY=<random, exactly 32 characters>
USER_AUTH_API_SECRET=<random, at least 32 characters>
@@ -0,0 +1,4 @@
# Every Java service. JWT_TOKEN: HS512 key, at least 32 characters; mobile-api's JWT_SECRET must be the same value.
JWT_TOKEN=<random, at least 32 characters>
MYSQLUSER=<database user from the DBA>
MYSQLPWD=<its password>
@@ -0,0 +1,6 @@
# Optional while WhatsApp is off. One ACCESS_TOKEN and APP_SECRET per company code in WHATSAPP_COMPANIES.
WHATSAPP_VERIFY_TOKEN=<random, at least 32 characters>
WHATSAPP_INS_ACCESS_TOKEN=<permanent system user token>
WHATSAPP_INS_APP_SECRET=<meta app secret>
WHATSAPP_CV_ACCESS_TOKEN=<permanent system user token>
WHATSAPP_CV_APP_SECRET=<meta app secret>
+13
View File
@@ -0,0 +1,13 @@
#!/bin/sh
# Pins every Co-Lite image in the prod overlay to one commit SHA of main (openspec spec cluster-deployment).
# Roll back by running it with the previous SHA and applying again.
# deploy/set-release.sh <40-character commit sha>
set -eu
cd "$(dirname "$0")/.."
sha=${1:-}
printf '%s' "$sha" | grep -Eq '^[0-9a-f]{40}$' || { echo "usage: $0 <40-character commit sha of main>" >&2; exit 2; }
k=deploy/k8s/overlays/prod/kustomization.yaml
sed -i -E "s/^( newTag: )\"[0-9a-f]+\"$/\1\"$sha\"/" "$k"
n=$(grep -c "^ newTag: \"$sha\"$" "$k")
[ "$n" -eq 10 ] || { echo "set-release: expected 10 images at $sha, found $n" >&2; exit 1; }
echo "prod overlay now pins all 10 images to $sha"
+76 -79
View File
@@ -1,6 +1,6 @@
# Co-Lite Deployment Handover
This is for whoever deploys Co-Lite to the Kubernetes cluster. CI builds and publishes the images. The deployer writes the manifests and rolls them out. The database package goes to the DBA.
This is for whoever deploys Co-Lite to the Kubernetes cluster. CI builds and publishes the images. The manifests are in `deploy/k8s/` (Kustomize: a `base` and a `prod` overlay); the deployer fills in the cluster facts and Secrets and applies them. The database package goes to the DBA.
Spec: `openspec/specs/release-packaging/spec.md`. Local stack for comparison: `local/README.md`.
@@ -26,7 +26,7 @@ The Service names matter:
- mobile-api and the portal find the gateway and mobile-api through `APIGATEWAYURL` and `MOBILE_API_BASE_URL`.
**Health probes:**
- **Java services:** liveness `GET /actuator/health/liveness`, readiness `GET /actuator/health/readiness`. Spring Boot turns these on by itself on Kubernetes. `GET /actuator/health` also works everywhere.
- **Java services:** liveness `GET /actuator/health/liveness`, readiness `GET /actuator/health/readiness`. mobile-api does not switch these on by itself (measured: 404 without the setting), so the prod settings set `MANAGEMENT_HEALTH_PROBES_ENABLED=true` for every Java pod. Use the liveness path for the startup probe too: `GET /actuator/health` is 503 on service-email while no mail server is set.
- **Admin portal:** it has no health endpoint. Use a TCP probe on port 3000, or `GET /login`, which returns 200 without a session.
**The Java images run as root and listen on port 80** (the base image sets no user). A cluster that enforces `runAsNonRoot` or the restricted Pod Security level must allow them.
@@ -35,17 +35,60 @@ The Service names matter:
## 2. Order of setup
Everything below runs from the repository root, on `main`, with `kubectl` pointed at the cluster. The checks need only Docker.
1. The DBA prepares MySQL (section 3).
2. Create the Pub/Sub topics and the service-account key (section 5).
3. Create the Secrets and mounted files (sections 6 and 7).
4. Deploy, in this order:
3. **Fill in the cluster facts.** Replace every `<…>` in `deploy/k8s/overlays/prod/`:
- `settings.env`: `MYSQLHOST` (from the DBA) and `REDISHOST` (the existing Redis);
- `gcp.env`: `GCP_PROJECT`;
- `routes.yaml`: the Traefik cert resolver, in both routes.
The namespace is `co-lite` (`kustomization.yaml` and `namespace.yaml`). Commit these files: they hold no secrets.
4. **Create the Secrets.** Copy `deploy/k8s/secrets.example/` to `deploy/k8s/secrets/`. Git ignores that folder, so never commit it. Fill in every `<…>` (sections 6 and 7 say what each value is). Then:
```sh
deploy/create-secrets.sh --dry-run # checks every key is filled in; prints names, never values
deploy/create-secrets.sh # creates or updates the Secrets in the co-lite namespace
```
The script creates the `co-lite` namespace if it is missing. Leave `co-lite-whatsapp.env` out until WhatsApp is connected (step 9).
5. **Pick the release.** Choose a commit on `main` whose CI run pushed the images, and pin it:
```sh
deploy/set-release.sh <40-character commit sha>
deploy/check.sh --release # refuses any <…> left, a public route to an internal service, latest, or a second service-counter
```
6. **Apply:**
```sh
kubectl apply -k deploy/k8s/overlays/prod
kubectl -n co-lite rollout status deploy --timeout=10m
```
All ten Deployments start together; each Java pod gets up to 5 minutes to start. Starting them together has not been tried on the cluster yet. If a pod keeps restarting, apply in the old order instead and wait for each step to be ready:
1. `service-system`, `service-auth`, `service-counter`, `service-member`, `service-log`, `service-email`, `service-whatsapp`;
2. `api-gateway`;
3. `mobile-api`;
4. `admin-portal`.
5. Add the Traefik routes (section 8).
6. Connect WhatsApp in Meta (section 11). This can wait: until it is done, the inbox says "WhatsApp is not configured".
7. Sign in as the first admin at `https://co-lite.containerverse.dev` and set the real password. Then create the staff users under Users. The admin types each user's first password and passes it on in person. Each user must choose their own password at first sign-in. No email is needed.
Use `kubectl -n co-lite rollout restart deploy/<name>` once the services it calls are ready.
7. Commit the overlay with the new SHA, so `main` records what runs.
8. Check the Custom HTML frame header (section 8).
9. Connect WhatsApp in Meta (section 11) whenever you are ready. Until then the inbox says "WhatsApp is not configured". To switch it on: fill in `whatsapp.env` in the overlay and `co-lite-whatsapp.env` in `secrets/`, then run `create-secrets.sh` and apply again.
10. Sign in as the first admin at `https://co-lite.containerverse.dev` and set the real password. Then create the staff users under Users. The admin types each user's first password and passes it on in person. Each user must choose their own password at first sign-in. No email is needed.
**Rollback.** Run `deploy/set-release.sh <the previous sha>`, then `deploy/check.sh --release`, then apply again and wait for the rollout. The SHA history of `deploy/k8s/overlays/prod/kustomization.yaml` on `main` lists the releases. Database changes only go forward: roll back only to a SHA that works with the schema now in place. Each change's SQL in section 3 says whether older code still runs on it.
**Changing a setting.** Edit the `.env` file in the overlay and apply again. The settings ConfigMaps get a new name for each new content, so the pods that read them restart by themselves. **Changing a secret:** edit `deploy/k8s/secrets/`, run `create-secrets.sh`, then `kubectl -n co-lite rollout restart deploy/<name>` for the pods that read it. mobile-api needs no restart for the WhatsApp secrets (section 6).
**Left unset on purpose.** These settings keep their built-in defaults:
- the email provider keys (section 10);
- `SMSS360_EMAIL` and `CUSTOMER_PORTAL_BASE_URL`, which still point at Tastefully (section 10);
- `JUMIO_TOKEN` and `JUMIO_SECRET`;
- `XXL_JOB_TOKEN`.
**Cluster facts still to confirm before the first apply:**
- the Traefik cert resolver name;
- the Redis host and the MySQL host;
- the Pub/Sub project;
- whether the pull secret can be `co-lite-registry`, or the cluster already has one;
- whether the separate public-pages hostname (section 8) is wanted at go-live (it would be a third route in `routes.yaml`).
## 3. Database (for the DBA)
@@ -309,6 +352,8 @@ Generate each random value separately, for example with `openssl rand -base64 48
## 8. Traefik
The routes below are in `deploy/k8s/overlays/prod/routes.yaml`; `deploy/check.sh` fails if a route reaches anything else.
Route `co-lite.containerverse.dev` to the `admin-portal` Service on port 3000, with TLS. Only the admin portal is public: the browser talks to the portal, and the portal talks to `mobile-api` inside the cluster. Do not expose `mobile-api`, `api-gateway` or the services.
**WhatsApp webhook.** Meta must reach exactly one mobile-api path from the internet. Add a second route on the same host, for the path `/api/public/whatsapp/webhook` only (Traefik rule `Host(\`co-lite.containerverse.dev\`) && Path(\`/api/public/whatsapp/webhook\`)`), to the `mobile-api` Service on port 80. Expose no other mobile-api path. Every call on it is checked: a GET needs the verify token, and a POST needs Meta's signature under one of the configured app secrets (mobile-api checks it, and `service-whatsapp` checks it again).
@@ -323,76 +368,20 @@ QR registration pages (`/r/<code>`) are served by the admin portal on the same h
## 9. Secret templates
There is no template yet for `service-email` (its keys wait for the email provider) or `service-system` (its Jumio keys stay unset). Kubernetes Secrets hold base64 values. Encode each one with `printf '%s' 'value' | base64 -w0`. These are templates: replace every `<…>` and never commit the filled-in files.
The templates are in `deploy/k8s/secrets.example/`, one file per Secret, with placeholders only:
```yaml
apiVersion: v1
kind: Secret
metadata:
name: co-lite-shared
type: Opaque
data:
JWT_TOKEN: <base64>
MYSQLUSER: <base64>
MYSQLPWD: <base64>
---
apiVersion: v1
kind: Secret
metadata:
name: co-lite-service-auth
type: Opaque
data:
AES_SECRET_KEY: <base64>
USER_AUTH_API_SECRET: <base64>
---
apiVersion: v1
kind: Secret
metadata:
name: co-lite-mobile-api
type: Opaque
data:
APIKEY: <base64>
AUTH_API_KEYS: <base64>
JWT_SECRET: <base64, same value as JWT_TOKEN>
---
apiVersion: v1
kind: Secret
metadata:
name: co-lite-admin-portal
type: Opaque
data:
MOBILE_API_KEY: <base64>
SESSION_SECRET: <base64>
---
apiVersion: v1
kind: Secret
metadata:
name: co-lite-whatsapp
type: Opaque
data:
# mounted into both mobile-api and service-whatsapp; one ACCESS_TOKEN and APP_SECRET pair per company code
WHATSAPP_INS_ACCESS_TOKEN: <base64>
WHATSAPP_INS_APP_SECRET: <base64>
WHATSAPP_CV_ACCESS_TOKEN: <base64>
WHATSAPP_CV_APP_SECRET: <base64>
WHATSAPP_VERIFY_TOKEN: <base64>
---
apiVersion: v1
kind: Secret
metadata:
name: co-lite-gateway-appkeys
type: Opaque
data:
appkeys.json: <base64 of the whole appkeys.json file>
---
apiVersion: v1
kind: Secret
metadata:
name: co-lite-gcp-key
type: Opaque
data:
key.json: <base64 of the service-account JSON key>
```
| Template | Secret | Read by |
|---|---|---|
| `co-lite-shared.env` | `co-lite-shared`: `JWT_TOKEN`, `MYSQLUSER`, `MYSQLPWD` | every Java service (api-gateway only `JWT_TOKEN`) |
| `co-lite-service-auth.env` | `co-lite-service-auth` | service-auth |
| `co-lite-mobile-api.env` | `co-lite-mobile-api` | mobile-api |
| `co-lite-admin-portal.env` | `co-lite-admin-portal` | admin-portal |
| `co-lite-whatsapp.env` | `co-lite-whatsapp` (optional) | mobile-api and service-whatsapp |
| `co-lite-registry.env` | `co-lite-registry`, the image pull secret | every pod |
| `co-lite-gateway-appkeys/appkeys.json` | `co-lite-gateway-appkeys` | api-gateway (section 7) |
| `co-lite-gcp-key/key.json` | `co-lite-gcp-key` | every Java service except api-gateway and service-whatsapp |
`deploy/create-secrets.sh` turns the filled-in copy into Secrets (section 2, step 4). It refuses to change anything while any key is missing, empty or still a placeholder. There is still no template for `service-email` (its keys wait for the email provider) or `service-system` (its Jumio keys stay unset).
## 10. Known gaps at go-live
@@ -409,7 +398,7 @@ data:
- **Reference data from Tastefully.** It still holds some Tastefully business text (message templates with a phone number, bank account and form links; a public image bucket URL; Tastefully usernames in audit columns). Review it before go-live.
- **Other Tastefully defaults.** The sender addresses in `service-email` and the `CUSTOMER_PORTAL_BASE_URL` fallback point at Tastefully. Override them as described in section 6.
- **Leaked SMS key.** An SMS360 API key from Tastefully was in `service-email`'s config and is in git history. It has been removed from the config, but it must be rotated with SMS360 before go-live, by whoever owns that Tastefully account.
- **Deploy by SHA, not `latest`.** CI pushes the images one by one, so if a push fails halfway, `latest` can differ between images.
- **Deploy by SHA, not `latest`.** CI pushes the images one by one, so if a push fails halfway, `latest` can differ between images. `deploy/check.sh` refuses `latest`.
- **Chinese labels.** Staff switch the back office to 简体中文 with the language switcher, including on the sign-in page. The Chinese is a first pass, not checked by a native speaker. Grant `BO_MESSAGES` to the reviewer's role: under **Translations**, the **Missing Chinese** filter lists labels with no Chinese or with English copied in, and a saved change shows on the next page load. The list also holds about 3,400 labels inherited from Tastefully that Co-Lite never shows; the **Co-Lite labels only** box, ticked by default, hides them, and unticking it lists every label. Export and Import move all labels through a JSON file for review offline; import matches labels by code and never adds or removes languages. Grant `BO_LOCALES` only to whoever decides which languages staff can pick: English cannot be switched off. Only the back office is translated; visitor pages and emails keep their own wording.
- **Gateway paths for labels.** The gateway used to let every `/message/` path through without a user token. It now lets through only the label reads (`/message/catalogVersion`, `/message/getAllMessages/<area>`, `/message/getMessageJsonByAreaAndLocale/<area>/<locale>`, `/message/getMessageJsonForMobile/...`, the code lookups) and `GET /locale/findAllEnabled`. Saving, searching and the language writes need the user token mobile-api forwards. The gateway also gains a `/locale/**` route to services-system.
- **WhatsApp roles.** Staff need `BO_WHATSAPP` to see the inbox and their own chats. A WhatsApp admin needs both `BO_WHATSAPP` and `BO_WHATSAPP_ADMIN`: the menu entry and the page need the first, and the second adds every chat of the company, owner changes and template sync. A chat's owner is set automatically to the salesperson of the newest lead with that mobile number; an admin can set an owner by hand, which sticks until "Automatic" is chosen again. A user who is disabled or loses `BO_WHATSAPP` loses their chats to Unassigned.
@@ -422,7 +411,7 @@ data:
- A send that Meta accepts without a message id is stored as failed. A send that never gets an answer stays "Sending"; nothing sweeps it.
- Media is streamed with `;charset=UTF-8` added to its content type; browsers ignore it.
- Meta's media download address is not checked to be a Meta host before the access token is sent with it.
- **WhatsApp webhook and outages.** If `service-whatsapp` is down or answers with an error, the webhook answers 503 and Meta sends the event again, for up to 7 days; a message is never stored twice. The same happens right after `service-whatsapp` starts while `service-system` is unreachable. Keep `service-system` up before `service-whatsapp` (section 2).
- **WhatsApp webhook and outages.** If `service-whatsapp` is down or answers with an error, the webhook answers 503 and Meta sends the event again, for up to 7 days; a message is never stored twice. The same happens right after `service-whatsapp` starts while `service-system` is unreachable. So on the first apply, check that `service-system` is ready before Meta starts sending (section 2, step 6).
- **Client addresses for rate limits.** mobile-api takes a caller's address for its rate limits from the first entry of `X-Forwarded-For` when the header is present (`HttpReqRespUtils` in core-libs). On the webhook route, a caller can set that header itself and so pick its own limit bucket. The webhook still rejects anything Meta did not sign, so this only weakens the flood limit (6000 calls per 10 minutes per address). Check that Traefik replaces an `X-Forwarded-For` sent by an untrusted caller instead of passing it on (`forwardedHeaders.insecure` off, `trustedIPs` limited to real proxies).
- **Landing pages.**
@@ -465,10 +454,18 @@ Marketing builds public pages under **Events → Pages**. Each page has blocks (
- **Jump to the form.** To make a button jump to the sign-up form, give the form block a link name, for example `signup`, and link the button to `#signup`. Links inside a Custom HTML block work the same way: on the INS page, change the HTML's `#consult` links to `#signup`. A `#name` link inside the HTML that matches an `id` in that same HTML (such as `#top`) scrolls to that spot instead.
5. **Drafts of published pages.** Once a page is published, Save keeps the changes as a draft: visitors still see the published version, and the editor shows **Publish changes** and **Discard changes**. Preview shows the draft. The pages list marks such pages "Unpublished changes". Publish changes checks the page again (an ended event, for example, is refused at its field). Switching the status back to Draft and saving takes the page offline and drops the separate draft. Two people saving the same page overwrite each other's draft, last save wins.
6. **Templates and Duplicate.** New page offers a blank page, **Event sign-up** and **Service showcase**. A template fills the editor with sections and placeholder text; staff replace the text and choose the form's event before saving. **Duplicate** (on the list and in the editor) opens a copy titled "… (copy)" with slug "…-copy" as a new draft; nothing is stored until Save.
7. **Check.** Publish a page, open its address signed out, sign up through its form with `?utm_source=test` on the address, and check that the event lead shows source **Web page**, the page address and the campaign. Delete that test lead afterwards.
7. **The on-page editor.** On a screen 1024 px or wider, the editor shows the page itself on a canvas, as visitors see it, with **Desktop** (a 1280 px screen scaled to fit) and **Phone** (390 px). Staff click a heading, text, button label, card or FAQ entry and type; rich text gets a small toolbar; clicking an image opens the file picker. Clicking a section selects it: its settings (look, link name, button link, event) show in the side panel, and its toolbar moves, duplicates, deletes or drags it. **Add section** sits under each section. Undo and redo (Ctrl+Z, Ctrl+Shift+Z) go back up to 50 steps and survive Save. A refused save selects the section and shows the message at its field in the panel. Narrower windows keep the form editor; resizing switches between them without losing unsaved edits. Leaving with unsaved edits, by a menu link too, asks first.
8. **Custom HTML on the canvas.** The canvas shows a Custom HTML block as last saved, marked **Save to update** while its HTML has unsaved edits; it shows the new HTML after Save. Preview always shows the saved version.
9. **Check.** Publish a page, open its address signed out, sign up through its form with `?utm_source=test` on the address, and check that the event lead shows source **Web page**, the page address and the campaign. Delete that test lead afterwards.
A form stops taking sign-ups when its event is disabled, its end date has passed (Malaysia time), or the company has no privacy notice; the page then says sign-up is closed and still shows its other blocks. Sign-ups share the QR pages' rate limits.
**Release add-page-drafts-and-templates (SQL, in its OpenSpec change folder):** run `sql/01-page-draft.sql` (adds `cms_page.draft`) before the new services-counter starts, then deploy services-counter, mobile-api and the portal, then run `sql/02-draft-template-labels.sql`. Rollback: previous images, then `sql/99-rollback.sql`, which drops every unpublished draft, so publish or note them first.
**Release add-page-visual-editor (SQL, in its OpenSpec change folder):** portal only. Deploy the portal, then run `sql/01-visual-editor-labels.sql`. Rollback: the previous portal image, then `sql/99-rollback.sql` (labels only). No data changes.
**Release add-hero-signup-form (SQL, in its OpenSpec change folder):** deploy services-counter, mobile-api and the portal (any order), then run `sql/01-hero-form-labels.sql` (labels only). A hero section can now carry the sign-up form for an event, beside its text. Rollback: the previous images. A hero saved with an event keeps it in its JSON. The old code ignores it and shows the hero without a form, so add a Sign-up form section to those pages if you roll back.
**Release add-hero-full-width (SQL, in its OpenSpec change folder):** deploy services-counter, then the portal, then run `sql/01-hero-full-width-labels.sql` (labels only). Deploy services-counter first, because the portal's editor saves the new hero fields. A hero can now run full width, carry bullet points, and give its form card a heading. Custom HTML frames now shrink to fit short content and no longer leave a gap next to a full-width hero. Rollback: the previous images. Saved heroes keep the new fields in their JSON; the old code ignores them and shows the boxed hero. The old services-counter refuses to save a hero that has points or a form heading, so remove them before saving such a page.
**New portal dependencies:** `@tiptap/react`, `@tiptap/pm`, `@tiptap/starter-kit` and `@tiptap/extension-text-align` (the editor, loaded only on the editor screens), and `sanitize-html` (cleans page text on the server before it reaches a visitor). The image build installs them from `package-lock.json`; nothing to do by hand.
+46
View File
@@ -1491,6 +1491,36 @@ INSERT INTO message (code, content, area) SELECT 'PagesDiscardTitle', JSON_OBJEC
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '放弃未发布的修改?') WHERE LOWER(code) = LOWER('PagesDiscardTitle') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesDiscardMessage', JSON_OBJECT('en_US', 'Your unpublished changes to "{title}" will be lost. Visitors keep seeing the published version.', 'zh_CN', '“{title}”未发布的修改将会丢失。访客仍看到已发布的版本。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDiscardMessage') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '“{title}”未发布的修改将会丢失。访客仍看到已发布的版本。') WHERE LOWER(code) = LOWER('PagesDiscardMessage') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesLeaveTitle', JSON_OBJECT('en_US', 'Leave without saving?', 'zh_CN', '不保存就离开?'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesLeaveTitle') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '不保存就离开?') WHERE LOWER(code) = LOWER('PagesLeaveTitle') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesLeaveMessage', JSON_OBJECT('en_US', 'Your changes to this page are not saved. Leave and lose them?', 'zh_CN', '此页面的修改尚未保存。离开将丢失这些修改,确定离开吗?'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesLeaveMessage') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '此页面的修改尚未保存。离开将丢失这些修改,确定离开吗?') WHERE LOWER(code) = LOWER('PagesLeaveMessage') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesLeave', JSON_OBJECT('en_US', 'Leave', 'zh_CN', '离开'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesLeave') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '离开') WHERE LOWER(code) = LOWER('PagesLeave') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesSaveToUpdate', JSON_OBJECT('en_US', 'Save to update', 'zh_CN', '保存后更新'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesSaveToUpdate') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '保存后更新') WHERE LOWER(code) = LOWER('PagesSaveToUpdate') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesAddSection', JSON_OBJECT('en_US', 'Add section', 'zh_CN', '添加区块'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesAddSection') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '添加区块') WHERE LOWER(code) = LOWER('PagesAddSection') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesDragSection', JSON_OBJECT('en_US', 'Drag to move', 'zh_CN', '拖动以移动'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDragSection') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '拖动以移动') WHERE LOWER(code) = LOWER('PagesDragSection') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesDuplicateSection', JSON_OBJECT('en_US', 'Duplicate section', 'zh_CN', '复制区块'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDuplicateSection') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '复制区块') WHERE LOWER(code) = LOWER('PagesDuplicateSection') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesPageSettings', JSON_OBJECT('en_US', 'Page settings', 'zh_CN', '页面设置'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesPageSettings') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '页面设置') WHERE LOWER(code) = LOWER('PagesPageSettings') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesCanvas', JSON_OBJECT('en_US', 'Page canvas', 'zh_CN', '页面画布'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesCanvas') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '页面画布') WHERE LOWER(code) = LOWER('PagesCanvas') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesCanvasView', JSON_OBJECT('en_US', 'Canvas view', 'zh_CN', '画布视图'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesCanvasView') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '画布视图') WHERE LOWER(code) = LOWER('PagesCanvasView') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesDesktop', JSON_OBJECT('en_US', 'Desktop', 'zh_CN', '桌面'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDesktop') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '桌面') WHERE LOWER(code) = LOWER('PagesDesktop') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesPhone', JSON_OBJECT('en_US', 'Phone', 'zh_CN', '手机'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesPhone') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '手机') WHERE LOWER(code) = LOWER('PagesPhone') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesUndo', JSON_OBJECT('en_US', 'Undo', 'zh_CN', '撤销'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesUndo') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '撤销') WHERE LOWER(code) = LOWER('PagesUndo') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesRedo', JSON_OBJECT('en_US', 'Redo', 'zh_CN', '重做'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesRedo') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '重做') WHERE LOWER(code) = LOWER('PagesRedo') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesUntitled', JSON_OBJECT('en_US', 'Untitled page', 'zh_CN', '未命名页面'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesUntitled') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '未命名页面') WHERE LOWER(code) = LOWER('PagesUntitled') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesChangesPublished', JSON_OBJECT('en_US', 'Changes published.', 'zh_CN', '修改已发布。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesChangesPublished') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '修改已发布。') WHERE LOWER(code) = LOWER('PagesChangesPublished') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesChangesDiscarded', JSON_OBJECT('en_US', 'Changes discarded.', 'zh_CN', '修改已放弃。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesChangesDiscarded') AND area = 'A');
@@ -1683,6 +1713,20 @@ INSERT INTO message (code, content, area) SELECT 'PagesFormClosed', JSON_OBJECT(
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '报名已截止。') WHERE LOWER(code) = LOWER('PagesFormClosed') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesFormPreview', JSON_OBJECT('en_US', 'The sign-up form shows here on the published page.', 'zh_CN', '发布后的网页会在此显示报名表。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesFormPreview') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '发布后的网页会在此显示报名表。') WHERE LOWER(code) = LOWER('PagesFormPreview') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesHeroForm', JSON_OBJECT('en_US', 'Sign-up form', 'zh_CN', '报名表单'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesHeroForm') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '报名表单') WHERE LOWER(code) = LOWER('PagesHeroForm') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesNoForm', JSON_OBJECT('en_US', 'No form', 'zh_CN', '不显示表单'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesNoForm') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '不显示表单') WHERE LOWER(code) = LOWER('PagesNoForm') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesFullWidth', JSON_OBJECT('en_US', 'Full width', 'zh_CN', '全宽'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesFullWidth') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '全宽') WHERE LOWER(code) = LOWER('PagesFullWidth') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesPointN', JSON_OBJECT('en_US', 'Point {number}', 'zh_CN', '要点 {number}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesPointN') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '要点 {number}') WHERE LOWER(code) = LOWER('PagesPointN') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesAddPoint', JSON_OBJECT('en_US', 'Add point', 'zh_CN', '添加要点'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesAddPoint') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '添加要点') WHERE LOWER(code) = LOWER('PagesAddPoint') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesFormHeading', JSON_OBJECT('en_US', 'Form heading', 'zh_CN', '表单标题'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesFormHeading') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '表单标题') WHERE LOWER(code) = LOWER('PagesFormHeading') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesFormText', JSON_OBJECT('en_US', 'Form text', 'zh_CN', '表单说明'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesFormText') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '表单说明') WHERE LOWER(code) = LOWER('PagesFormText') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesToolbar', JSON_OBJECT('en_US', 'Formatting', 'zh_CN', '格式'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesToolbar') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '格式') WHERE LOWER(code) = LOWER('PagesToolbar') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesTextStyle', JSON_OBJECT('en_US', 'Text style', 'zh_CN', '文字样式'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTextStyle') AND area = 'A');
@@ -1717,6 +1761,8 @@ INSERT INTO message (code, content, area) SELECT 'PagesLink', JSON_OBJECT('en_US
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '链接') WHERE LOWER(code) = LOWER('PagesLink') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesLinkPrompt', JSON_OBJECT('en_US', 'Link address (https://, mailto:, tel:, / or #name)', 'zh_CN', '链接地址(https://、mailto:、tel:、/ 或 #名称)'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesLinkPrompt') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '链接地址(https://、mailto:、tel:、/ 或 #名称)') WHERE LOWER(code) = LOWER('PagesLinkPrompt') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesLinkRefused', JSON_OBJECT('en_US', 'That link is not allowed. Use https://, mailto:, tel:, a path starting with / or #name.', 'zh_CN', '不允许此链接。请使用 https://、mailto:、tel:、以 / 开头的路径或 #名称。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesLinkRefused') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '不允许此链接。请使用 https://、mailto:、tel:、以 / 开头的路径或 #名称。') WHERE LOWER(code) = LOWER('PagesLinkRefused') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesClearFormatting', JSON_OBJECT('en_US', 'Clear formatting', 'zh_CN', '清除格式'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesClearFormatting') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '清除格式') WHERE LOWER(code) = LOWER('PagesClearFormatting') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesTooManyBlocks', JSON_OBJECT('en_US', 'A page can have at most 30 blocks.', 'zh_CN', '每个网页最多 30 个区块。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTooManyBlocks') AND area = 'A');
@@ -0,0 +1,43 @@
# Proposal
## Why
Event pages convert best when the sign-up form is visible as soon as the page opens. INS's standalone landing page (`~/Projects/ins-landing-page`) puts the form in a card beside the hero text. In Co-Lite the form is always its own section, so on a page built from Custom HTML it lands below the hero, and the hero tells visitors to "scroll down to the form". Custom HTML cannot hold the real form: it runs in a sealed frame that cannot send leads into Co-Lite.
## What Changes
- A HERO block gains an optional event (`eventUuid`). When it is set, the hero shows Co-Lite's sign-up form for that event in a card beside the heading, text and button on wide screens, and below them on phones.
- The hero form behaves exactly like the FORM block:
- the same fields, interests and privacy notice;
- the same submit rules and limits;
- the same lead source, UTM values and closing rules.
- The server checks a hero's event like a FORM block's: it must be an event of the page's company.
- In the editor, the Hero's settings gain the same event picker as the Sign-up form, with "No form" as the default. The canvas shows the form card in place.
- Switching company in the editor clears a hero's event, as it already clears a FORM block's.
Not changing:
- The FORM block stays as it is.
- A page may have a hero form and a FORM block together, and each registers for its own event.
- The form card has no heading of its own; the hero's heading and text introduce it.
## Capabilities
### New Capabilities
None.
### Modified Capabilities
- `landing-pages`: hero blocks may carry the sign-up form, and the event-reference rule covers them.
## Impact
- **services-counter:** `CmsBlockValidator`, which now checks a HERO's optional `eventUuid`.
- **mobile-api:** `PublicPageService`, which attaches form info to, and accepts submits for, any block with an event (FORM or a HERO that has one).
- **admin-portal:**
- the `HERO` rendering in `CmsBlocks.tsx`;
- the Hero fields in `BlockFields.tsx`;
- the company-switch reset in `usePageDraft.ts`;
- two labels, in English and Chinese.
- **No schema change:** blocks are JSON.
- **No new dependency.**
@@ -0,0 +1,48 @@
## ADDED Requirements
### Requirement: Hero With A Sign-Up Form
A HERO block MAY name an event. When it does, the hero SHALL show Co-Lite's sign-up form for that event in a card beside its heading, text and button on wide screens, and below them on narrow screens. The hero's form SHALL follow every rule of the FORM block (see "The Form Block Registers For An Event" and "The Form Block Closes With Its Event"). A HERO block without an event SHALL show no form.
#### Scenario: Sign up from the hero
- **GIVEN** page `/p/INS/hotel-technology` has a HERO block whose event is `INS website enquiries`
- **WHEN** a new visitor submits the form in the hero from a URL with `utm_source=facebook`
- **THEN** a new lead and an event lead with source Web page, no salesperson and UTM source `facebook` are created
#### Scenario: Hero form closes with its event
- **GIVEN** the HERO block's event ended yesterday
- **WHEN** a visitor opens the page
- **THEN** the hero still shows its heading and text, and its form area says sign-up is closed
#### Scenario: Hero without an event
- **WHEN** a visitor opens a page whose HERO block names no event
- **THEN** the hero shows no form
- **AND** a submit addressed to that block is refused as not found
#### Scenario: Pick the hero's event in the editor
- **GIVEN** staff editing a page with a HERO block
- **WHEN** they pick `INS website enquiries` under the hero's sign-up form setting
- **THEN** the canvas shows the form card beside the hero text
- **AND** choosing "No form" removes it
## MODIFIED Requirements
### Requirement: Block References Stay Inside The Company
A block's image SHALL be an image of the page's company, and the event of a FORM block or of a HERO block that names one SHALL be an event of the page's company. Otherwise the save SHALL be refused on that field.
#### Scenario: Another company's event
- **GIVEN** event `CV Roadshow` belongs to CV
- **WHEN** INS staff save a FORM block pointing at `CV Roadshow`
- **THEN** the save is refused on that block's event field
#### Scenario: Another company's event in a hero
- **GIVEN** event `CV Roadshow` belongs to CV
- **WHEN** INS staff save a HERO block whose event is `CV Roadshow`
- **THEN** the save is refused on that block's event field
@@ -0,0 +1,7 @@
-- The labels added by add-hero-signup-form, cut from the output of `npm run i18n:sql`. Run it only in an environment that already ran add-zh-cn-messages/sql/03-zh-cn-messages.sql; otherwise run that 03 file, which includes these labels.
SET NAMES utf8mb4;
USE `service-system`;
INSERT INTO message (code, content, area) SELECT 'PagesHeroForm', JSON_OBJECT('en_US', 'Sign-up form', 'zh_CN', '报名表单'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesHeroForm') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '报名表单') WHERE LOWER(code) = LOWER('PagesHeroForm') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesNoForm', JSON_OBJECT('en_US', 'No form', 'zh_CN', '不显示表单'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesNoForm') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '不显示表单') WHERE LOWER(code) = LOWER('PagesNoForm') AND area = 'A';
@@ -0,0 +1,39 @@
# Tasks
## 1. Server
- [x] 1.1 services-counter `CmsBlockValidator`: a HERO's optional `eventUuid` must be an event of the page's company, refused at `blocks[n].eventUuid` with `PagesBadEvent`. Verify: new validator tests (own event saves, other company's event refused, no event saves) fail first, then pass; `mvn -T 1C -pl solvway-services-counter verify`.
- [x] 1.2 mobile-api `PublicPageService`: `page()` attaches `form`/`closed` to every block with an event that is FORM or HERO; `submit()` accepts a HERO with an event and refuses a HERO without one as not found. Verify: new service tests fail first, then pass; `mvn -T 1C -pl solvway-mobile-api verify`.
## 2. Portal
- [x] 2.1 `CmsBlocks.tsx` HERO: with `form` or `closed`, two columns from `md` (text left, form card right; stacked on phones), image and shade kept; the card is `LandingForm` with the hero's block index. Verify: render tests for with/without event, closed, and the edit canvas; vitest exit 0.
- [x] 2.2 `BlockFields.tsx`: the Hero gets the event picker ("No form" default, same hint and unavailable-event option as FORM; `eventUuid` shown inline); `usePageDraft` clears a HERO's event on company switch like a FORM's; labels `PagesHeroForm` and `PagesNoForm` in `defaultMessages.ts`, `zh_CN.seed.json` and an SQL label file in this change folder. Verify: editor tests fail first, then pass; tsc and lint clean.
## 3. Verification
- [x] 3.1 Rebuild services-counter and mobile-api locally; Playwright on port 3001: give a page's hero an event, see the card beside the text at 1280 px and below it at 390 px, submit as a visitor on the published page and see the lead under Event leads with source Web page; pick another company's event is impossible in the picker, and an ended event shows "closed". Use a disposable test page and the existing "LP Enquiries" test event; delete the test page after.
- [x] 3.2 Full portal vitest (exit 0), tsc, lint, both Maven modules, `openspec validate add-hero-signup-form --strict`.
## Notes (2026-12-03)
- **Red first:** each new test failed before its code existed. The validator test failed on the foreign event; the service tests found no form on the hero; the render tests, the editor picker test and the company-switch test failed too.
- **Existing editor test:** one query was scoped to the FORM block's picker, because "Website enquiries" is now an option in two pickers. Its assertions are unchanged.
- **Live check** (port 3001, rebuilt counter and mobile-api), on the throwaway page "Live check hero form":
- the hero picker defaults to "No form";
- the canvas shows the card beside the text;
- published at 1280 px, the form sits beside the text, and at 390 px below it;
- the visitor "Hero Check Visitor" registered from the hero and appears under INS website enquiries with "Web page: /p/INS/live-check-hero-form";
- the page was deleted afterwards. The test lead stays in the local database.
- **Fixes from the live check:**
- the hero text is top-aligned, because a long form left it below the fold;
- the top padding is larger, so the editor's image button clears the heading;
- the shade is a gradient, because the design-token test refuses flat `bg-black/*`.
- **Not checked live:**
- the closed state, which the picker cannot reach because it offers no ended events (covered by the service and render tests);
- the other-company refusal, which the picker cannot reach either (covered by the validator test).
- **Results:** Maven verify passed for services-counter and mobile-api; vitest 1985 passed (exit 0); tsc clean; lint 0 errors.
## Workflow follow-up
- PR to `main` and merge; archive on its own branch with its own PR.
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-12-03
@@ -0,0 +1,124 @@
# Design
## Context
- **Images:** CI publishes ten images to `gitea.containerverse.dev/solvway/`, each tagged with the commit SHA and with `latest`.
- **What `docs/deployment.md` already fixes:**
- the Service names and ports;
- the probes;
- every environment variable, and whether it is secret or plain;
- the two mounted files (`appkeys.json` for the gateway, the Pub/Sub `key.json` for the other Java images);
- the setup order;
- the Traefik routes (portal on `co-lite.containerverse.dev`, plus the webhook path).
- **Outside the cluster manifests:**
- MySQL, prepared by the DBA;
- Redis ("use the existing Redis");
- Google Pub/Sub.
- **Tools:** the repository has no Kubernetes files, and this machine has Docker but no kubectl.
## Goals / Non-Goals
**Goals:**
- One `kubectl apply -k deploy/k8s/overlays/prod` deploys the whole system once the Secrets exist.
- A check that fails on the mistakes that would hurt in production:
- a public route to an internal service;
- an image on `latest`;
- secret data in git;
- two service-counter replicas.
**Non-Goals:**
- Helm charts, GitOps tooling (Argo CD or Flux), or automatic deploys from CI. A person applies each release.
- Running MySQL, Redis or a Pub/Sub emulator in the cluster.
- A local Kubernetes preview. The owner previews the system with the docker-compose stack.
- Autoscaling, resource tuning beyond sensible requests, and NetworkPolicies. These can follow once the cluster's policy is known.
## Decisions
### 1. Kustomize, with a base and a `prod` overlay
- **Choice:** plain YAML under `deploy/k8s/base/`, plus `deploy/k8s/overlays/prod/` for the image SHA, the plain settings, the namespace and the routes.
- **Why:**
- Kustomize is built into kubectl, so the deployer installs nothing.
- The YAML reads like the handover doc.
- **Rejected:**
- Helm: templating for one environment adds code, and Helm would need installing.
- Raw YAML without overlays: the SHA would then be edited in ten files.
### 2. The image SHA is set in one place
- **How:** the overlay's `images:` list sets `newTag` for all ten images. A small `deploy/set-release.sh <sha>` rewrites those ten lines.
- **Rollback:** run `set-release.sh <previous sha>` and apply again. Every release is a commit on `main`, so the SHA in git history is the record of what ran.
### 3. Secrets are created by a script from git-ignored files, not stored as manifests
- **Templates:** `deploy/k8s/secrets.example/` holds one `.env` template per Secret (from `docs/deployment.md` section 9), plus an `appkeys.json` template.
- **Filling them in:** the deployer copies the folder to `deploy/k8s/secrets/`, which git ignores, and fills it in.
- **Creating them:** `deploy/create-secrets.sh` runs `kubectl create secret generic --from-env-file / --from-file ... --dry-run=client -o yaml | kubectl apply -f -`. It never prints a value.
- **Rejected:**
- Sealed Secrets or SOPS: new tooling and keys to manage, for a two-developer team. They can come later.
- A Kustomize `secretGenerator`: it would put the values into the rendered output, which the check must stay able to forbid.
### 4. Traefik IngressRoute for the public routes
- **What:** the `prod` overlay holds two IngressRoutes on `co-lite.containerverse.dev`:
- `/` to `admin-portal:3000`;
- `Path(/api/public/whatsapp/webhook)` to `mobile-api:80`.
- **Why:** the handover doc already states the routes as Traefik rules, and the cluster runs Traefik.
- **TLS:** a `tls:` block whose cert resolver (or cert-manager secret) name is a single field in the overlay (see Open Questions).
- **Rejected:** a standard Ingress with Traefik annotations. Exact-path matching is less clear there, and nothing else in the cluster needs portability.
### 5. The check runs from one pinned container
- **What:** `deploy/check.sh` sends the `deploy/` folder through stdin into `alpine/k8s:1.33.4`, pinned by digest. That one image has kubectl and kustomize, kubeconform, and python3 with PyYAML.
- **Why stdin:** it also works against CI's remote Docker daemon, where bind mounts would not reach the files.
- **Steps:**
1. Kustomize renders the overlay.
2. kubeconform validates the result. The Traefik schemas come from the CRDs catalog.
3. `check_rules.py` applies the rules.
- **Modes:**
- `--self-test` runs every rule against its fixture in `deploy/check-fixtures/`.
- `--release` also refuses any `<…>` placeholder. CI runs the plain check, because the cluster facts are still placeholders in git; the deployer runs `--release` before applying.
- **Rejected:** separate kubectl, kubeconform and Python images. That is three pulls and three pins for the same result.
### 6. Pod settings
- **Common to all pods:**
- one replica each;
- `TZ` left to the image;
- `GCP_CREDENTIAL_FILE` and the `key.json` mount on every Java pod except `api-gateway` and `service-whatsapp`;
- `imagePullSecrets` set to one named pull secret.
- **service-counter:** `strategy: Recreate`, so a rollout never runs two copies at once and the daily summary is never sent twice.
- **Probes:** the startup probe uses `/actuator/health/liveness` and allows up to 5 minutes. The overall `/actuator/health` is 503 on service-email while no mail server is configured.
- mobile-api does not turn its probe groups on by itself, so the settings set `MANAGEMENT_HEALTH_PROBES_ENABLED=true` for every Java pod.
- Both facts were measured on the local containers.
- **WhatsApp Secret:** referenced with `optional: true`, so mobile-api and service-whatsapp start while WhatsApp is off.
- **Image tags:** quoted in the overlay. A SHA made only of digits, or shaped like `1e45…`, would otherwise be read as a number.
- **Requests:** modest (`100m` CPU and `512Mi` for the Java pods; `256Mi` for the portal), with no CPU limit. `JAVA_OPTS=-Xmx384m` keeps the heap inside the memory limit.
- **Security context:** the Java images run as root (documented). The manifests do not set `runAsNonRoot`. If the cluster enforces it, that is a finding for the image, not a manifest workaround.
## Risks / Trade-offs
- **[A wrong cluster fact breaks the first apply]** (CRD version, pull-secret name, TLS method). Mitigation: those facts are single overlay fields, listed under Open Questions, and the first apply is done together with the owner.
- **[Secrets created by hand drift from the templates]** Mitigation: `create-secrets.sh` refuses to run if any key in a template is missing from the filled file.
- **[No automatic deploy means releases lag `main`]** This is accepted for go-live. Every release is a deliberate act with a recorded SHA.
- **[The check uses an image pulled from Docker Hub]** Mitigation: it is pinned by version and digest.
- **[kubeconform fetches the Traefik schema from GitHub]** Without network access the check fails rather than skipping. CI already needs the network to pull images.
## Migration Plan
1. The DBA prepares MySQL, and the Pub/Sub topics and key are created (handover sections 3 and 5).
2. Fill in `deploy/k8s/secrets/` and run `deploy/create-secrets.sh`. Create the registry pull secret.
3. Run `deploy/set-release.sh <sha>` and `deploy/check.sh`, then `kubectl apply -k deploy/k8s/overlays/prod`.
4. Wait for every Deployment to roll out (`kubectl rollout status`), then sign in as the first admin.
5. **Rollback:** run `set-release.sh <previous sha>`, apply again, and wait for the rollout. Database changes are forward-only. A release that ran new SQL rolls back only to a SHA that works with that schema; the SQL files say which ones are safe.
## Open Questions
These are single overlay fields. They are needed before the first real apply, not to build or check the manifests.
- **Namespace:** the default is `co-lite`.
- **TLS:** the Traefik cert resolver name (for example `letsencrypt`), or a cert-manager ClusterIssuer.
- **Pull secret:** its name for `gitea.containerverse.dev`, if the cluster already has one.
- **Redis:** the address of "the existing Redis".
- **Public-pages hostname:** the separate one for `/r`, `/i`, `/c` and `/p` (handover section 8), if it should exist at go-live.
- **Access:** who has kubectl access to the cluster for the first apply.
@@ -0,0 +1,46 @@
# Proposal
## Why
Phase 1 ends with Co-Lite running on the team's Kubernetes cluster before go-live on 15 January 2027. CI already publishes the images, and `docs/deployment.md` describes the environment the images need. Nobody has written the Kubernetes manifests yet, so every deploy would be typed by hand from a long document. That invites mistakes in the things that matter most: which paths are public, where secrets come from, and which image version runs.
## What Changes
- Add a `deploy/k8s/` folder with Kustomize manifests for the whole system:
- a Deployment and a Service for each of the ten images in `docs/deployment.md` section 1, with the names, ports, health probes and settings it lists;
- a `prod` overlay that pins every image to one commit SHA, sets the plain settings, and routes the public host through Traefik with TLS.
- Expose only two things to the internet: the admin portal, and mobile-api's WhatsApp webhook path. Nothing else gets a route.
- Keep every secret out of git. The manifests only refer to Secrets and mounted files by name. Add a checked-in template and a script that creates them from local files the deployer fills in and never commits.
- Add a check script, run locally and in CI, that renders the manifests and fails if:
- a route reaches anything other than the portal or the webhook path;
- an image uses `latest`;
- a Secret value appears in the rendered output;
- service-counter has more than one replica.
- Update `docs/deployment.md` so the deploy steps use the manifests (`kubectl apply -k`) instead of describing them in prose. Add the rollback steps.
Out of scope:
- MySQL and Redis: the DBA's MySQL and the existing Redis stay outside the cluster manifests.
- The Pub/Sub project and key.
- Choosing an email provider.
- Connecting WhatsApp in Meta.
## Capabilities
### New Capabilities
- `cluster-deployment`: how Co-Lite is described and rolled out on Kubernetes. It covers what is exposed publicly, how secrets are supplied, how image versions are pinned, and how a release is rolled back.
### Modified Capabilities
None. `release-packaging` (how images are built and published) does not change.
## Impact
- **New:** `deploy/k8s/` (base and `prod` overlay), `deploy/k8s/secrets.example/`, `deploy/check.sh`.
- **Changed:** `docs/deployment.md` and `.gitea/workflows/ci.yml` (one manifest-check step).
- **No application code changes.**
- **No new dependencies in the repo.** The check runs `kubectl kustomize` and kubeconform from pinned container images, so the machine needs only Docker.
- **The real cluster needs:**
- Traefik, with its IngressRoute CRD;
- a pull secret for `gitea.containerverse.dev`;
- the DNS record for `co-lite.containerverse.dev`.
@@ -0,0 +1,88 @@
# Spec Delta
## Purpose
Describe how Co-Lite is rolled out to Kubernetes from manifests in the repository, so that public exposure, secrets, image versions and rollback are fixed in reviewed files rather than typed by hand.
## ADDED Requirements
### Requirement: One manifest set deploys the whole system
The repository SHALL hold Kubernetes manifests that create a Deployment and a Service for each published image. The Service names and ports MUST be the ones the gateway, mobile-api and the portal already expect (`docs/deployment.md` section 1). Each Java service MUST have liveness and readiness probes on its actuator health endpoints. The admin portal MUST have a probe that needs no session.
#### Scenario: Apply brings every service up
- **GIVEN** a cluster where the Secrets, the mounted files, the database and the image pull secret already exist
- **WHEN** the deployer applies the `prod` overlay
- **THEN** a Deployment and a Service exist for all ten images under the expected names and ports
- **AND** every pod becomes ready
#### Scenario: Unhealthy pod gets no traffic
- **GIVEN** a Java service whose readiness endpoint reports down
- **WHEN** Kubernetes checks the pod
- **THEN** the pod is not ready and its Service sends it no requests
### Requirement: Only the portal and the WhatsApp webhook are public
The manifests SHALL route the public host, over TLS, to the admin-portal Service. They SHALL route exactly the path `/api/public/whatsapp/webhook` to the mobile-api Service. No other Service may be reachable from outside the cluster. The repository's manifest check MUST fail when a route targets any other Service or path.
#### Scenario: Gateway is not reachable from the internet
- **WHEN** the rendered `prod` manifests are checked
- **THEN** no route targets `api-gateway` or any `service-*`
- **AND** the only route to `mobile-api` matches exactly `/api/public/whatsapp/webhook`
#### Scenario: A new route is caught
- **GIVEN** a manifest change that adds a route to `api-gateway`
- **WHEN** the manifest check runs
- **THEN** it fails and names the route
### Requirement: Secrets never enter the repository
The manifests SHALL refer to Secrets and mounted files only by name. The repository MUST NOT hold any real secret value. Secret templates hold placeholders only. The script that creates the Secrets MUST read the values from files that git ignores.
#### Scenario: Rendered manifests hold no secret data
- **WHEN** the `prod` overlay is rendered
- **THEN** it contains no `Secret` object with data
- **AND** the manifest check fails if one appears
#### Scenario: Filled-in secret files cannot be committed
- **GIVEN** a deployer who fills in the secret files under the secrets folder
- **WHEN** they run `git status`
- **THEN** those files are ignored
### Requirement: Releases are pinned by commit and can be rolled back
The `prod` overlay SHALL pin every image to one commit SHA, never `latest`. Rolling back MUST be done by setting the previous SHA and applying again. The deployment docs MUST describe both steps. Before a real apply, a release check MUST refuse any cluster fact still left as a placeholder.
#### Scenario: latest is refused
- **GIVEN** a `prod` overlay where an image tag is `latest` or missing
- **WHEN** the manifest check runs
- **THEN** it fails and names the image
#### Scenario: Unfilled cluster fact refused before apply
- **GIVEN** a `prod` overlay that still holds a `<…>` placeholder, such as the MySQL host
- **WHEN** the deployer runs the release check
- **THEN** it fails and names each placeholder
#### Scenario: Roll back to the previous release
- **GIVEN** a release at SHA B that misbehaves, with SHA A deployed before it
- **WHEN** the deployer sets the overlay to SHA A and applies it
- **THEN** every Deployment rolls back to the SHA A images
### Requirement: Single-run jobs stay single
service-counter SHALL run as exactly one replica. It sends the daily follow-up summary, and two replicas would send it twice. The manifest check MUST fail when service-counter has more than one replica.
#### Scenario: Counter scaled by mistake
- **GIVEN** a manifest change that sets service-counter to two replicas
- **WHEN** the manifest check runs
- **THEN** it fails
@@ -0,0 +1,84 @@
# Tasks
## 1. Manifest check first (red)
- [x] 1.1 Add `deploy/check.sh` and its rule script.
- The script renders `deploy/k8s/overlays/prod` with pinned kubectl and kubeconform images, then applies the four rules:
- public routes reach only the portal and the exact webhook path;
- no image on `latest` or without a tag;
- no Secret data in the output;
- service-counter has exactly one replica.
- Add rule fixtures under `deploy/check-fixtures/`: one passing set and one failing set per rule.
- Verify: `deploy/check.sh --self-test` fails each bad fixture with a message naming the offending object, and passes the good one.
- Running it against the still-missing overlay fails.
- Done: 12 fixtures (one per rule, plus `bad-placeholder.yaml` for `--release`). The first red run passed on an empty render, so the container now stops on the first error, and `--full` requires all ten Deployments and Services.
## 2. Base manifests
- [x] 2.1 Add `deploy/k8s/base/`: a Deployment and a Service for each of the ten images, with the names, ports, probes, environment (secret refs and plain values) and mounts from `docs/deployment.md` sections 1, 6 and 7.
- service-counter: one replica, `strategy: Recreate`.
- Verify: `kubectl kustomize deploy/k8s/base`, run in the check container, renders the ten Deployments and ten Services. kubeconform passes.
- Done: 20 resources, all valid. The probe paths were checked against the running local containers. Two fixes came out of that:
- mobile-api answered 404 on liveness and readiness, so `MANAGEMENT_HEALTH_PROBES_ENABLED=true` is now in the settings;
- service-email's overall health is 503 without a mail server, so the startup probe uses the liveness path.
- [x] 2.2 Cross-check the base against `local/docker-compose.yml`: every variable a service reads locally is either set or deliberately left unset in the base.
- Verify: a scripted diff of the variable names per service shows no unexplained gaps. Record the deliberate ones in `docs/deployment.md`.
- Done: every `${…}` in each `application.yml` is supplied. Deliberately unset: the email keys, `SMSS360_EMAIL`, `CUSTOMER_PORTAL_BASE_URL`, Jumio, and `XXL_JOB_TOKEN` (listed in section 2).
- The WhatsApp Secret reference is `optional: true`, so mobile-api starts while WhatsApp is off.
## 3. Prod overlay, release pinning and routes
- [x] 3.1 Add `deploy/k8s/overlays/prod/`. It sets:
- the namespace;
- the `images:` list with one SHA for all ten images;
- the plain settings (`ADMIN_PORTAL_BASE_URL`, `REDISHOST`, `MYSQLHOST`, `GCP_PROJECT` and the rest);
- the pull secret;
- two Traefik IngressRoutes with TLS.
Verify: `deploy/check.sh` passes on the overlay (task 1 goes green).
- [x] 3.2 Add `deploy/set-release.sh <sha>`, which rewrites the overlay's ten tags.
- Verify: run it with a test SHA, then confirm that `check.sh` passes and `git diff` shows exactly ten tag lines changed. Running it with `latest` or a non-hex value is refused.
- Done: ten lines change. Running it with `latest` or a short SHA is refused.
- An all-digit SHA broke the render (YAML read it as a number), so the tags are now quoted. `2222…` and `1e45…` both render and pass.
## 4. Secrets
- [x] 4.1 Add `deploy/k8s/secrets.example/`: one `.env` template per Secret, plus an `appkeys.json` and a `key.json` placeholder, all with placeholders only.
- Add `deploy/k8s/secrets/` to `.gitignore`.
- Verify: a filled-in file under `deploy/k8s/secrets/` is listed by `git check-ignore`.
- [x] 4.2 Add `deploy/create-secrets.sh`. It creates or updates each Secret through `kubectl create ... --dry-run=client -o yaml | kubectl apply -f -`. It refuses if a template key is missing or still holds a placeholder, and it never prints a value.
- Verify: run it with `--dry-run` against a filled test folder; it prints only the Secret names and the key names.
- Verify: a missing key is refused, and the refusal names the key.
- Done: the dry run lists seven Secrets with their key names only. A missing `MYSQLPWD` is refused, and so is a placeholder `MYSQLPWD`.
- The real path ran in the check container, with `kubectl apply` stubbed:
- the `co-lite` namespace is created first, because the first run comes before any apply;
- seven Secrets carry the right keys and decode to the filled values;
- the registry Secret is a dockerconfigjson for `gitea.containerverse.dev`;
- no value appears on stdout.
- mobile-api's probes were proven on a throwaway container. Without `MANAGEMENT_HEALTH_PROBES_ENABLED` its liveness and readiness paths are missing; with it, all three return 200.
## 5. CI and docs
- [x] 5.1 Add a `deploy/check.sh` step to `.gitea/workflows/ci.yml`, before the image push.
- Verify: the workflow file parses, and the step runs locally with the same command.
- [x] 5.2 Rewrite the deploy steps in `docs/deployment.md` (sections 2 and 9) around the manifests:
- create the Secrets, set the release, run the check, apply, wait for the rollout;
- roll back;
- list the open cluster facts from `design.md`.
Verify: following the doc's commands in order against the check container renders and passes.
## 6. Verification
- [x] 6.1 Run the full check: `deploy/check.sh` and its self-test, the repository's existing build and tests (unchanged), and `openspec validate add-k8s-deployment --strict`.
- Done: the check and the self-test pass, and `openspec validate --strict` passes.
- Maven and vitest were not re-run: no module source or build file changed. Only `deploy/`, `docs/`, `.gitignore` and the CI file changed.
- [ ] 6.2 Run a server-side dry run against the real cluster: `kubectl apply -k deploy/k8s/overlays/prod --dry-run=server`, by the owner or with the owner's cluster access. Record the result here.
- This needs the open cluster facts filled in and access to the cluster. If access is not available before archive, leave the task unticked with a note, as was done for the WhatsApp e2e.
- Open (2026-12-03): there is no cluster access from this machine, and the cluster facts are not yet given. Owed by the owner with the first real apply.
## Workflow follow-up
- Branch from `origin/main`, then open a PR to `main` and merge it.
- Archive the change on its own branch, with its own PR.
- The first real apply happens with the owner, after the database package and Secrets are in place.
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-12-03
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-12-03
@@ -0,0 +1,109 @@
# Design: add-page-visual-editor
## Context
- **Design doc:** `docs/superpowers/specs/2026-12-03-page-builder-design.md`, change 3. Changes 1 and 2 are live: section types and looks, draft and live content, templates, and Duplicate.
- **Today's editor** is `app/components/pages/PageEditor.tsx`, about 415 lines. It holds all page state and actions:
- load, the draft, `show`, images uploaded on save;
- save, publish changes, discard and delete;
- mapping refusals to fields.
- **Block fields** are edited by `BlockFields.tsx`.
- **Rendering.** The public page and the preview render with `LandingPage` and `Block` in `CmsBlocks.tsx`. Custom HTML renders through `HtmlFrame`, a sealed frame loaded from a frame address that skips the nonce policy.
- **Page policy.** The baseline CSP sets no `style-src`. Scripts need the per-request nonce.
## Goals / Non-Goals
**Goals**
- Edit the page on the page, with Desktop and Phone views.
- Text editing in place, section actions and undo.
- Change 2's draft controls and entries kept.
- The form editor kept below 1024 px.
**Non-Goals**
- Free placement or per-element styling.
- Version history.
- Editing on phones.
- Live rendering of unsaved Custom HTML.
- Any server or API change.
## Decisions
### 1. The canvas is a blank same-origin frame that the editor renders into
The editor mounts `<iframe>` with no `src` (about:blank, same origin), then renders the page into its body with `createPortal`.
**Styles and theme.**
- The `<link rel=stylesheet>` and `<style>` elements in the editor's `<head>` are cloned into the frame. A MutationObserver keeps them in step when `next dev` swaps them.
- `<html>`'s `class`, `data-theme` and `style` are copied, which carries the Inter font variable, the dark class and the variables.
**Why the frame.** It has its own viewport, so `sm:`, `md:` and `lg:` respond to the canvas width, as on a visitor's device. React context (messages, auth) and events work through the portal, and there is a single copy of the draft.
**Rejected: a canvas address that exchanges the draft by `postMessage`,** as the design doc sketched. It needs a sync protocol both ways, origin checks and a second copy of the draft, which makes undo and in-place editing harder.
**Security.** The canvas frame has no `sandbox`, unlike every other frame in the portal. It must be same-origin for the portal, and a sandbox without `allow-scripts` would also stop the scripts of the Custom HTML frames nested in it. It holds no data HTML: its only document is a constant blank page (`srcDoc`, no `src`), and everything in it is React-rendered as on the preview page. The portal's markup sweep test allow-lists exactly that file, constant and shape.
**Fallback.** Task 1 is a spike with pass criteria. If it fails (Tiptap inside the frame, focus, drag events, or production CSS), use a canvas route `/pages/canvas` that reads the draft and posts edits back. Only the canvas wiring changes.
### 2. Desktop is 1280 px, scaled
- **Desktop** renders the frame 1280 px wide and scales it with a CSS transform to the width left beside the panel. The frame is one screen tall and scrolls inside, like a device. A frame grown to its content risks a feedback loop with the page's `min-h-svh`, and a fixed screen keeps `svh` honest.
- **Phone** is 390 px at 1:1.
- Outlines, toolbars and "Add section" buttons are drawn inside the frame document, so they scale with the page.
### 3. Edit-mode hooks in `LandingPage`
- An optional `edit` prop on `LandingPage` provides an `EditContext`. Without it, rendering is unchanged, and the public page and preview never pass it.
- **Plain text fields.** In edit mode, `Block` renders text fields through `<EditableText field=… max=…>`: a `contentEditable="plaintext-only"` element. It reports input on each keystroke and is never re-rendered from props while it has focus, so the caret stays.
- **Rich text** (RICH_TEXT and IMAGE_TEXT html) renders through the existing `RichTextEditor`. A `bare` option adds a floating toolbar and drops the boxed look. It uses the same `isSafeLink` rule.
- **Images.** An image spot is a button that opens a file input in the editor document. The chosen file previews from a data URL, as today.
- **`Section`** gains `data-index`, an outline when hovered or selected, and the toolbar. Gaps get "+ Add section".
- **Clicks.** Clicks on links, buttons and the form are prevented in edit mode. The FORM block already renders its preview note.
### 4. `HtmlFrame` listens on its own window
- It adds its message listener to `ref.current.ownerDocument.defaultView`. Inside the canvas, the sealed frame's parent is the canvas window, so the height and anchor messages arrive there.
- The canvas passes `frameBase` = the preview frame address (saved draft). Changing a block's HTML sets "Save to update" on that block until the next save. After Save, the frame reloads with a cache-busting `?v=<save count>`.
### 5. Shared state: `usePageDraft`
`PageEditor`'s state and actions move, unchanged, into `usePageDraft(pageId, fromId, initialBlocks)`. Both editors use it. This is a refactor guarded by the existing editor tests. The visual editor adds:
- **`selected` index** (or none).
- **History.** Arrays of `{ draft, rows }` snapshots, up to 50.
- A text field pushes one snapshot when it gains focus and changes.
- A structural action pushes one before it applies.
- Undo and redo replace the state and blur the focused editable first, so a focused field is re-rendered from the restored value.
- Ctrl+Z inside a rich-text field is Tiptap's own undo while that field has focus. Page undo applies after blur.
- **Refusal mapping.** A refused field `blocks[i].…` sets `selected = i` and scrolls the section into view in the frame. The panel then shows `BlockFields` errors as today.
### 6. Layout
```
┌ ← Pages Title [status] [Desktop|Phone] ↶ ↷ [Duplicate][Preview][View page][Delete] [Save] ┐
├ unpublished-changes banner (Publish changes / Discard changes), as in change 2 ──────────────────┤
├──────────────────── canvas ───────────────────────────────────┬──── panel (360 px) ────────────┤
```
- **Panel.** It shows `BlockFields` for the selected block, which already covers every field, the look and the link name. With nothing selected it shows the page settings card and the status card from today's form.
- **Which editor.** `matchMedia("(min-width: 1024px)")` chooses the editor. Resizing across the line switches editors with the state kept, since both use the same hook.
### 7. Leave guard for in-app links
A capture-phase click listener on `document`, active while there are unsaved changes, catches same-origin `<a href>` clicks that would leave the page. It shows the existing `ConfirmDialog`; Leave then calls `router.push`. This replaces the gap noted in `PageEditor` (`ponytail:` comment). Browser back is not guarded; this is named in the comment.
### 8. Drag and drop
Drag and drop uses native HTML5 events on the section handle inside the frame, with a drop line between sections. Keyboard users use up and down. jsdom cannot run native drag-and-drop, so the reorder function is unit-tested and the drag itself is checked live.
## Risks / Trade-offs
- **Tiptap or focus inside a portal frame.** ProseMirror reads `ownerDocument` in most places, but this is unverified for selection handling in a frame. The spike covers it, and the fallback is in Decision 1.
- **Style cloning in production.** A production build serves hashed CSS links, which clone fine. The spike checks a `next build` once, not only `next dev`.
- **Two editors share one hook.** Each keeps its own tests. The form editor stays the narrow-window path, and the fallback if the canvas misbehaves.
- **Saved-only Custom HTML on the canvas.** Accepted: staff paste HTML rarely. The marker says what they see.
## Migration Plan
- Portal-only deploy, then run `sql/01-visual-editor-labels.sql`.
- Rollback: the previous portal image, then `sql/99-rollback.sql` (labels).
- No data change.
@@ -0,0 +1,51 @@
# Proposal: add-page-visual-editor
## Why
INS and CV marketing staff build a page for every event and are not technical. Today they fill in a form of blocks and check a separate preview of the last saved version. The owner asked for a Wix-like editor: staff click the page itself to change it and see the result as they work. This is change 3 of the page builder (`docs/superpowers/specs/2026-12-03-page-builder-design.md`). Changes 1 (sections) and 2 (drafts, templates, Duplicate) are live.
## What Changes
- **On-page editor** at 1024 px and wider. The page renders in a canvas inside the editor, at the desktop width scaled to fit, or at phone width (390 px). It uses the same `LandingPage` rendering as visitors see. A side panel shows the selected section's settings, or the page settings when no section is selected.
- **Edit in place.**
- Headings, short texts, button labels, card titles and texts, and FAQ questions and answers are edited as plain text on the canvas, with the server's length limits.
- Rich text (Text, and Image with text) is edited in place with a small toolbar.
- Clicking an image spot opens the file picker.
- **Section actions.** Select, a toolbar (drag handle, up, down, duplicate, delete), and "+ Add section" between sections and at the end.
- **Undo and redo** for the page, up to 50 steps, with Ctrl+Z, Ctrl+Shift+Z and buttons.
- **Change 2 carried over.** The editor's top bar keeps Save, Preview, View page, Duplicate, Delete, the unpublished-changes banner with Publish changes and Discard changes, and the status. Templates and Duplicate open in the new editor.
- **Refusals on the canvas.** A refused field's section is selected and outlined, and the panel shows the message at the field.
- **Unsaved changes.** In-app links now ask before leaving with unsaved changes, in both editors. Today only reload and close ask.
- **Below 1024 px** the current form editor stays, with Preview.
### Departures from the approved design doc
These are builder calls, recorded in `design.md`:
1. **Canvas wiring.** The editor renders the page into a blank same-origin frame itself, instead of loading a canvas address that exchanges the draft by `postMessage`. There is one copy of the draft and no message protocol. A spike task proves it first, with a canvas route as the named fallback.
2. **Desktop view** renders at 1280 px and is scaled down to fit beside the panel, so the page's own breakpoints match a desktop visitor's. "Full width" would show the tablet layout on a laptop.
3. **Custom HTML** on the canvas shows the last saved version, with a "Save to update" mark once its HTML is edited. It reloads after Save. Unsaved pasted HTML cannot run sealed with today's frame routes and script policy.
## Capabilities
### New Capabilities
None.
### Modified Capabilities
- `landing-pages`:
- The Page Editor, Saving And Deleting In The Editor, The Custom HTML Block In The Editor, and New Sections In The Editor change.
- The on-page editor requirements are added: canvas, editing in place, section actions, undo, and refusals on the canvas.
## Impact
- **Portal only:**
- New: `app/components/pages/visual/*` (canvas, panel, top bar, history).
- `PageEditor` state moves into a shared hook used by both editors.
- `CmsBlocks` gains edit-mode hooks, which the public page does not use.
- `HtmlFrame` listens on the window of the document it is in.
- A leave guard for in-app links.
- **Security:** the editor canvas is the portal's only frame without a `sandbox`. It must be same-origin for the editor to render into it, and a sandbox would also stop scripts in the Custom HTML frames nested inside. It loads only a constant blank document with no `src`, so no stored HTML ever runs as the portal. The markup sweep test allow-lists exactly that file and shape (design Decision 1).
- **No server, API, database or SQL changes.** New labels only, with a label SQL file.
- **No new dependencies.** Tiptap is already installed; dragging uses native drag-and-drop.
@@ -0,0 +1,133 @@
## MODIFIED Requirements
### Requirement: The Page Editor
At 1024 px and wider the editor SHALL be the on-page editor. Below 1024 px it SHALL be the form editor. Both SHALL offer the title, a slug filled from the title until edited, a meta description with a 160-character counter, the status, adding, moving and removing blocks, and images uploaded only on save. A FORM block SHALL pick from the company's enabled events that have not ended.
#### Scenario: Slug follows the title until edited
- **GIVEN** a new page
- **WHEN** staff type the title "Hotel Technology"
- **THEN** the slug becomes `hotel-technology`
#### Scenario: Narrow window keeps the form
- **WHEN** staff open a page in a window 900 px wide
- **THEN** the form editor shows, with Preview
### Requirement: Saving And Deleting In The Editor
Server field errors SHALL show at their fields, keeping all entered values. After a save the editor SHALL offer a link to view the page. Deleting a page SHALL ask first. With unsaved edits, reloading, closing and following an in-app link SHALL ask first.
#### Scenario: Server error at its field
- **WHEN** staff save a HERO button link `javascript:alert(1)`
- **THEN** the error shows at that button link and every entered value stays
#### Scenario: Leaving by an in-app link
- **GIVEN** staff changed a heading and did not save
- **WHEN** they click Pages in the menu
- **THEN** the editor asks before leaving, and Cancel keeps them on the page with the change
### Requirement: The Custom HTML Block In The Editor
The editor SHALL offer adding a Custom HTML block, edited in a monospace text box with a 200000-character counter and a note that forms inside it do not send. On the canvas the block SHALL show its last saved version as a sealed frame, marked "Save to update" while its HTML has unsaved edits. The editor SHALL offer a "hide page header" switch.
#### Scenario: Adding a Custom HTML block
- **WHEN** staff add a Custom HTML block and paste HTML into it
- **THEN** the block shows the pasted HTML, the character count and the note about forms
#### Scenario: Unsaved HTML on the canvas
- **GIVEN** a saved page with a Custom HTML block
- **WHEN** staff change its HTML in the panel
- **THEN** the canvas marks the block "Save to update"
- **AND** after Save the canvas shows the new HTML
#### Scenario: Hiding the header
- **WHEN** staff turn on "hide page header" and save
- **THEN** reading the page returns "hide header" on
### Requirement: New Sections In The Editor
Both editors SHALL offer adding FEATURES, STEPS, TRUST and CTA blocks, editing their fields, adding, removing and reordering cards, and choosing any block's look. Refusals SHALL show at the field they name, including card fields.
#### Scenario: A refused card title shows at its field
- **GIVEN** staff editing a page with a FEATURES block
- **WHEN** the save is refused on field `blocks[0].cards[1].title`
- **THEN** the message shows at the second card's title field
## ADDED Requirements
### Requirement: The Page Canvas
The on-page editor SHALL show the page on a canvas, rendered as visitors see it, with a Desktop view (1280 px wide, scaled to fit) and a Phone view (390 px wide). Changes SHALL show on the canvas as they are made, before saving. Links and buttons on the canvas SHALL NOT navigate, and the sign-up form SHALL show its preview note.
#### Scenario: Phone view uses the phone layout
- **GIVEN** a page with a FEATURES block of three cards
- **WHEN** staff switch to Phone
- **THEN** the cards stack in one column on the canvas
#### Scenario: A change shows before saving
- **WHEN** staff change a FEATURES card title in the side panel
- **THEN** the canvas shows the new title at once
### Requirement: Edit Text On The Page
Clicking a heading, short text, button label, card title or text, or FAQ question or answer on the canvas SHALL edit it in place as plain text, with the server's length limit shown when close. Rich text SHALL be edited in place with bold, italic, link, lists and alignment, and links SHALL follow the page link rule. An empty field SHALL show a faded cue naming it, and empty rich text SHALL keep room to click into. Clicking an image spot SHALL open the file picker.
#### Scenario: Edit a heading in place
- **WHEN** staff click the hero heading on the canvas and type "Hotel week"
- **THEN** the canvas and the side panel show "Hotel week"
#### Scenario: An unsafe link is refused in rich text
- **WHEN** staff add the link `javascript:alert(1)` in a Text block on the canvas
- **THEN** the link is not added and the toolbar says why
### Requirement: Section Selection And Actions
Clicking a section on the canvas SHALL select it, outline it and show its settings in the side panel. With none selected, the panel SHALL show the page settings. A selected section SHALL offer drag, up, down, duplicate and delete. "Add section" between sections and at the end SHALL offer every block type. Up and down SHALL work from the keyboard. A section that is added, duplicated or moved SHALL be brought into view on the canvas.
#### Scenario: Duplicate a section
- **WHEN** staff select the second section and press Duplicate
- **THEN** a copy appears as the third section and is selected
#### Scenario: Add a section between two
- **WHEN** staff press Add section between the first and second sections and choose Steps
- **THEN** a Steps section appears second and is selected
#### Scenario: Add a section from the side panel
- **GIVEN** the canvas shows the top of a long page
- **WHEN** staff press Add Text in the side panel
- **THEN** the canvas scrolls to the new Text section at the end, which shows a faded "Content" cue to type into
### Requirement: Undo And Redo
The on-page editor SHALL undo and redo page changes, up to 50 steps, by buttons and by Ctrl+Z and Ctrl+Shift+Z. The keys SHALL work wherever focus is in the editor, including after the focused control is removed or disabled, except inside a field outside the editor. Typing in one field SHALL be one step. Saving SHALL NOT clear the history.
#### Scenario: Undo a delete
- **GIVEN** staff deleted the FAQ section
- **WHEN** they press Ctrl+Z
- **THEN** the FAQ section is back in its place with its content
### Requirement: Refusals On The Canvas
When a save or publish is refused on a block field, the editor SHALL select that block, outline it, scroll it into view and show the message at the field in the side panel. A refusal on a page field SHALL show in the page settings.
#### Scenario: A form without an event
- **GIVEN** a page from the Event sign-up template
- **WHEN** staff save without choosing the form's event
- **THEN** the form section is selected and outlined and the panel shows the message at the Event field
@@ -0,0 +1,35 @@
-- The labels added by add-page-visual-editor, cut from the output of `npm run i18n:sql`. Run it only in an environment that already ran add-zh-cn-messages/sql/03-zh-cn-messages.sql; otherwise run that 03 file, which includes these labels.
SET NAMES utf8mb4;
USE `service-system`;
INSERT INTO message (code, content, area) SELECT 'PagesLeaveTitle', JSON_OBJECT('en_US', 'Leave without saving?', 'zh_CN', '不保存就离开?'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesLeaveTitle') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '不保存就离开?') WHERE LOWER(code) = LOWER('PagesLeaveTitle') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesLeaveMessage', JSON_OBJECT('en_US', 'Your changes to this page are not saved. Leave and lose them?', 'zh_CN', '此页面的修改尚未保存。离开将丢失这些修改,确定离开吗?'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesLeaveMessage') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '此页面的修改尚未保存。离开将丢失这些修改,确定离开吗?') WHERE LOWER(code) = LOWER('PagesLeaveMessage') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesLeave', JSON_OBJECT('en_US', 'Leave', 'zh_CN', '离开'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesLeave') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '离开') WHERE LOWER(code) = LOWER('PagesLeave') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesSaveToUpdate', JSON_OBJECT('en_US', 'Save to update', 'zh_CN', '保存后更新'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesSaveToUpdate') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '保存后更新') WHERE LOWER(code) = LOWER('PagesSaveToUpdate') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesLinkRefused', JSON_OBJECT('en_US', 'That link is not allowed. Use https://, mailto:, tel:, a path starting with / or #name.', 'zh_CN', '不允许此链接。请使用 https://、mailto:、tel:、以 / 开头的路径或 #名称。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesLinkRefused') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '不允许此链接。请使用 https://、mailto:、tel:、以 / 开头的路径或 #名称。') WHERE LOWER(code) = LOWER('PagesLinkRefused') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesAddSection', JSON_OBJECT('en_US', 'Add section', 'zh_CN', '添加区块'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesAddSection') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '添加区块') WHERE LOWER(code) = LOWER('PagesAddSection') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesDragSection', JSON_OBJECT('en_US', 'Drag to move', 'zh_CN', '拖动以移动'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDragSection') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '拖动以移动') WHERE LOWER(code) = LOWER('PagesDragSection') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesDuplicateSection', JSON_OBJECT('en_US', 'Duplicate section', 'zh_CN', '复制区块'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDuplicateSection') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '复制区块') WHERE LOWER(code) = LOWER('PagesDuplicateSection') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesPageSettings', JSON_OBJECT('en_US', 'Page settings', 'zh_CN', '页面设置'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesPageSettings') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '页面设置') WHERE LOWER(code) = LOWER('PagesPageSettings') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesCanvas', JSON_OBJECT('en_US', 'Page canvas', 'zh_CN', '页面画布'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesCanvas') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '页面画布') WHERE LOWER(code) = LOWER('PagesCanvas') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesCanvasView', JSON_OBJECT('en_US', 'Canvas view', 'zh_CN', '画布视图'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesCanvasView') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '画布视图') WHERE LOWER(code) = LOWER('PagesCanvasView') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesDesktop', JSON_OBJECT('en_US', 'Desktop', 'zh_CN', '桌面'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDesktop') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '桌面') WHERE LOWER(code) = LOWER('PagesDesktop') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesPhone', JSON_OBJECT('en_US', 'Phone', 'zh_CN', '手机'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesPhone') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '手机') WHERE LOWER(code) = LOWER('PagesPhone') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesUndo', JSON_OBJECT('en_US', 'Undo', 'zh_CN', '撤销'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesUndo') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '撤销') WHERE LOWER(code) = LOWER('PagesUndo') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesRedo', JSON_OBJECT('en_US', 'Redo', 'zh_CN', '重做'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesRedo') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '重做') WHERE LOWER(code) = LOWER('PagesRedo') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesUntitled', JSON_OBJECT('en_US', 'Untitled page', 'zh_CN', '未命名页面'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesUntitled') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '未命名页面') WHERE LOWER(code) = LOWER('PagesUntitled') AND area = 'A';
@@ -0,0 +1,3 @@
-- Co-Lite change add-page-visual-editor: rollback. Deploy the previous portal image first; this only removes its labels.
USE `service-system`;
DELETE FROM message WHERE code IN ('PagesLeaveTitle', 'PagesLeaveMessage', 'PagesLeave', 'PagesSaveToUpdate', 'PagesLinkRefused', 'PagesAddSection', 'PagesDragSection', 'PagesDuplicateSection', 'PagesPageSettings', 'PagesCanvas', 'PagesCanvasView', 'PagesDesktop', 'PagesPhone', 'PagesUndo', 'PagesRedo', 'PagesUntitled') AND area = 'A';
@@ -0,0 +1,58 @@
# Tasks: add-page-visual-editor
Design: `design.md`. Every task is TDD. Work is serial in the main session, with a self-review per task.
- Verify (portal): `cd solvway-admin-portal && npx vitest run; echo VITEST=$? && npx tsc --noEmit && npm run lint`
## 1. Foundations
- [x] 1.1 **Spike, kept only if it passes:** render `LandingPage` into a blank frame by portal, with copied styles and theme. It passes when all of these work, in `next dev` and in one `next build` + `next start`:
- Tailwind breakpoints follow the frame width (390 vs 1280).
- Fonts and dark mode look right.
- A Tiptap editor inside the frame types, selects and applies bold.
- A `contentEditable` field keeps its caret while typing.
- Native drag events fire.
- A Custom HTML frame inside it reports its height.
On failure, stop and switch to the canvas-route fallback (design Decision 1), noting why.
Passed 2026-12-03 in `next dev` and `next build` + `next start`: 390 px stacks the cards and 1280 px shows three columns; Inter and dark mode follow the editor live; Tiptap typed and applied bold; a plain field kept its caret; dragstart and drop fired inside the scaled frame; a Custom HTML frame grew to 4419 px after 1.2. The frame scrolls inside rather than growing (design Decision 2).
- [x] 1.2 `HtmlFrame` listens on its own document's window (test: a frame inside another document still resizes).
- [x] 1.3 Move `PageEditor` state and actions into `usePageDraft`, with no behaviour change. All existing `PageEditor*.test.tsx` stay green and unchanged.
- [x] 1.4 Leave guard for in-app links in the form editor (test: an in-app link click with unsaved edits asks; Cancel stays, Leave navigates).
## 2. Canvas
- [x] 2.1 `PageCanvas`: the frame, the Desktop view (1280 px scaled) and the Phone view (390 px), live updates from the draft, and links and buttons inert.
- [x] 2.2 Edit-mode hooks in `CmsBlocks`: `EditContext`, `EditableText` for every plain text field with its server limit, image spots, `Section` outline and `data-index`. Public rendering stays unchanged: the existing `CmsBlocks*.test.tsx` stay green.
- [x] 2.3 Rich text in place: `RichTextEditor` bare mode with a floating toolbar (test: an unsafe link is refused with a message).
- [x] 2.4 Custom HTML on the canvas: the saved-draft frame, the "Save to update" mark, and a reload after save.
## 3. Editor
- [x] 3.1 `VisualEditor` layout:
- The top bar: title, status, Desktop and Phone, undo and redo, Duplicate, Preview, View page, Delete, Save.
- The change 2 banner with Publish changes and Discard changes.
- The side panel: `BlockFields` for the selected block, or the page settings.
- The editor is chosen by width, 1024 px and up.
- [x] 3.2 Selection and section actions: select, toolbar (up, down, duplicate, delete), "Add section" between sections and at the end, native drag reorder (reorder function unit-tested), and the keyboard path.
- [x] 3.3 Undo and redo: history of 50, one step per field edit and per action, Ctrl+Z and Ctrl+Shift+Z, kept across saves.
- [x] 3.4 Refusals on the canvas: select, outline, scroll into view, message at the panel field; page-field refusals in the page settings.
- [x] 3.5 Templates (`?template=`) and Duplicate (`?from=`) open in the visual editor.
- [x] 3.6 Labels in `defaultMessages.ts` and `zh_CN.seed.json`, `npm run i18n:sql`, `sql/01-visual-editor-labels.sql`, `sql/99-rollback.sql`.
## 4. Release
- [x] 4.1 `docs/deployment.md` §12: the on-page editor for staff, the narrow-window form, and Custom HTML showing after Save.
- [x] 4.2 Live check with Playwright (snapshot, find and screenshots only; no `eval`), on disposable pages, at 1280 px and at 900 px for the form, with Desktop and Phone views:
- Create from a template, edit headings and a card in place, change a look in the panel, and add, duplicate, move and delete sections.
- Undo and redo.
- Save without an event: the form is outlined with the message at Event.
- Choose the event and save. Publish changes.
- Rich text with a safe link and a refused unsafe one.
- A Custom HTML block: the "Save to update" mark, then the new HTML after save.
- Leaving by a menu link with unsaved changes.
- Done 2026-12-03, re-run on fresh code after a full reload: Fast Refresh had not applied edits on this page. Also checked: one undo step per Ctrl+Z from three places, drag to reorder, Look, and Duplicate and Move up revealing their section. Found and fixed on the way:
- Ctrl+Z did nothing right after a toolbar delete: focus fell to the canvas body.
- Ctrl+Z also did nothing once Redo went disabled: focus fell to the page body.
- A new empty Text section was a thin line under its Add section button.
- A section added from the panel stayed out of view.
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-12-04
@@ -0,0 +1,25 @@
# Design
## Context
The HERO block renders inside `Section`, which wraps every non-HTML block in the page width (`max-w-5xl px-4`). The page's block list is `space-y-10`. Custom HTML blocks already render outside `Section`, so they run full width. The hero-with-form layout comes from add-hero-signup-form.
## Approaches
1. **A `fullWidth` option on HERO (chosen).** Explicit and opt-in, so existing heroes and templates do not change. It costs one boolean and one switch in the editor.
2. **Make every hero with a form full width.** This needs no new field, but it silently changes existing pages and ties two unrelated choices together.
3. **Build the hero in Custom HTML.** This cannot work: a sealed frame cannot hold the real sign-up form (see add-hero-signup-form).
## Decisions
- **Points reuse `cards`.** They use title-only cards, as the trust strip does. The DTO does not change, and the editor reuses the trust strip's item list (`PagesItemN`, `PagesAddItem`). On a HERO the validator allows 0 to 6 cards. FEATURES, STEPS and TRUST keep their 2 to 6 rule.
- **Joins.** A block counts as "bleed" when it is HTML, or when it is a full-width HERO. When a block and the block before it are both bleed, the block gets no top margin. Two Custom HTML blocks next to each other therefore join as well. That changes current pages, but only toward what Custom HTML sections expect: built sections are designed to stack.
- **A full-width hero is not wrapped in `Section`.** It renders outside the page width, in the same way as `HtmlSpot`. Its inner content uses a wider container (`max-w-6xl px-4`).
- **Font.** The headline uses Tailwind's `font-serif`, the system serif. No web font is added, so there is no new dependency and no third-party request.
- **Shade.** The full-width shade is a left-to-right gradient, from `black/75` through `black/45` to `black/10`. It stays black-based, because the design-token test refuses raw colours, and the white text sits on the dark side. On phones the layout stacks and the form card is solid, so contrast holds.
- **Form heading and text.** These are plain text fields edited with `Text` in place, in the same way as the hero heading. They are refused on a hero without an event, so they cannot hide in saved data.
## Risks
- **Contrast with a light photo on the right.** The text sits on the left, over the darkest part of the shade, and the right side holds the solid form card. This is acceptable.
- **Editor controls on the edge.** On the full-width canvas, the image button and the toolbar sit at the window's edge. They are already positioned inside the section by the PR #66 fix.
@@ -0,0 +1,59 @@
# Proposal
## Why
The INS Hotel technology page is being rebuilt in Co-Lite to match INS's standalone landing page (`~/Projects/ins-landing-page`). Since add-hero-signup-form, the form sits beside the hero text, but the hero still looks unlike the original in five ways:
- it is a rounded box inside the page width, with grey space around it, where the original runs edge to edge directly under the top bar;
- its shade is near-black over the whole photo, where the original fades from dark on the left to a clear photo on the right;
- its headline is small and pinned to the top, where the original's is large, serif and vertically centred;
- it has no bullet points under the text;
- the form card has no title or subtitle ("Get a free consultation" / "Tell us about your property…").
Marketing staff cannot fix any of these from the editor.
## What Changes
- A HERO block gains a **Full width** option (`fullWidth`). A full-width hero:
- spans the whole window, with square corners and no page margin;
- is taller, with a larger serif headline, vertically centred;
- uses a lighter shade that runs from dark on the left to almost clear on the right.
- Full-width heroes and Custom HTML blocks that sit next to each other join with no gap, so a Custom HTML top bar runs straight into the hero.
- Custom HTML frames (found in the live check):
- they may shrink to 20 px instead of 100 px, so a 68 px top bar leaves no blank band;
- the page asks each frame for its height once it listens and when the frame loads, because the frame's first report could arrive before the page was ready, leaving it at 600 px.
- A HERO block may carry up to 6 **points**, short title-only lines (`cards`, 80 characters each) shown as a bullet list under its text. The editor reuses the trust strip's item list.
- A HERO with an event may carry a **form heading** (`formHeading`, 80 characters) and **form text** (`formText`, 200 characters), shown at the top of the form card. Both can be typed in place on the canvas.
- The server validates the new fields:
- `fullWidth` is a boolean;
- the hero takes 0 to 6 points, each a non-empty title of at most 80 characters, with no icon or text;
- the form heading and form text are refused on a hero without an event.
- New editor labels in English and Chinese, with an SQL label file for real environments.
Not changing:
- The heroes that exist today. Without the option they look as they do now.
- The sign-up form's fields, the privacy notice and the consent box. They are shared with QR sign-up, and the notice and consent are required by the data-protection rules.
- Field labels and the interests checkboxes.
- The submit button colour, which follows the company's accent colour. For INS's gold button, set INS's accent colour in Companies; that is a setting, not code.
- The red wave decoration at the bottom of the INS hero, which is left out.
## Capabilities
### New Capabilities
None.
### Modified Capabilities
- `landing-pages`: adds "Full-Width Hero", "Hero Points" and "Hero Form Heading".
## Impact
- services-counter: `CmsBlock` gains `fullWidth`, `formHeading` and `formText`. `CmsBlockValidator` lets a HERO carry `cards` as points and checks the new fields.
- mobile-api: none. Public blocks pass through as maps.
- Portal:
- `CmsBlocks.tsx` renders the hero layout and the joins between full-width blocks;
- `BlockFields.tsx` gets the Full width switch, the points list and the form heading and text;
- `cmsPages.ts` gets the types;
- new labels in `defaultMessages.ts` and `zh_CN.seed.json`.
- Data: no schema change, because the blocks are JSON. The new labels need a SQL label file in this change folder for real environments.
@@ -0,0 +1,86 @@
## ADDED Requirements
### Requirement: Full-Width Hero
A HERO block MAY be marked full width. A full-width hero SHALL span the whole window with square corners, show its heading larger and centred top to bottom in the hero's opening height (not beside a long form), and use a shade that is darker on the text side than on the far side. A hero that is not marked full width SHALL look as it did before. The server SHALL refuse a `fullWidth` value that is not true or false.
#### Scenario: Hero runs edge to edge under a Custom HTML top bar
- **GIVEN** page `/p/INS/hotel-technology` with a Custom HTML top bar followed by a full-width HERO with an image and an event
- **WHEN** a visitor opens the page in a 1280 px window
- **THEN** the hero spans the full window width
- **AND** the form card sits beside the heading
#### Scenario: Existing hero unchanged
- **WHEN** a visitor opens a page whose HERO block is not marked full width
- **THEN** the hero sits inside the page width with rounded corners, as before
#### Scenario: Turn on full width in the editor
- **GIVEN** staff editing a page with a HERO block
- **WHEN** they switch on "Full width" in the hero's settings
- **THEN** the canvas shows the hero across the full width
### Requirement: Full-Width Blocks Join Without Gaps
A full-width HERO and a Custom HTML block next to each other SHALL join with no gap between them, and so SHALL two Custom HTML blocks next to each other. Other blocks SHALL keep their usual spacing.
#### Scenario: Top bar runs straight into the hero
- **GIVEN** a Custom HTML top bar followed by a full-width HERO
- **WHEN** a visitor opens the page
- **THEN** the hero starts directly under the top bar, with no gap
### Requirement: Hero Points
A HERO block MAY carry up to 6 points, each a non-empty title of at most 80 characters, with no icon and no text. The hero SHALL show its points as a bulleted list under its text. The server SHALL refuse more than 6 points, an empty or over-long point, and a point with an icon or text, naming the field.
#### Scenario: Points under the hero text
- **GIVEN** a HERO block with points "One accountable partner instead of five vendors" and "Local support team in Malaysia"
- **WHEN** a visitor opens the page
- **THEN** both points show as a bulleted list under the hero text
#### Scenario: Too many points refused
- **WHEN** staff save a HERO block with 7 points
- **THEN** the save is refused at `blocks[n].cards`
### Requirement: Hero Form Heading
A HERO block with an event MAY carry a form heading of at most 80 characters and a form text of at most 200 characters. The hero SHALL show them at the top of its form card, above the form. The server SHALL refuse either on a hero without an event. On the canvas, staff SHALL be able to type both in place.
#### Scenario: Card shows its heading
- **GIVEN** a HERO block with an event, form heading "Get a free consultation" and form text "Tell us about your property. It takes under a minute."
- **WHEN** a visitor opens the page
- **THEN** the form card starts with that heading and text, followed by the form
#### Scenario: Form heading without a form refused
- **WHEN** staff save a HERO block with a form heading and no event
- **THEN** the save is refused at `blocks[n].formHeading`
## MODIFIED Requirements
### Requirement: Custom HTML Frame Height
The frame SHALL grow or shrink to fit its content, between 20 and 20000 pixels, using height reports sent by that frame only. Before the first report it SHALL be 600 pixels tall. The frame SHALL report the height of its content, not of its own window, and SHALL report again whenever the page asks, which the page SHALL do once it listens and when the frame loads.
#### Scenario: A tall paste grows the frame
- **GIVEN** a published HTML block whose content is 3000 pixels tall
- **WHEN** a visitor opens the page
- **THEN** the frame is 3000 pixels tall and shows no inner scroll bar
#### Scenario: A short top bar shrinks the frame
- **GIVEN** a published HTML block holding only a 68 pixel top bar
- **WHEN** a visitor opens the page, even if the frame loaded before the page was ready
- **THEN** the frame is 68 pixels tall, with no blank space below the bar
#### Scenario: Another frame cannot resize it
- **WHEN** a different window posts a height report to the page
- **THEN** the frame's height does not change
@@ -0,0 +1,13 @@
-- The labels added by add-hero-full-width, cut from the output of `npm run i18n:sql`. Run it only in an environment that already ran add-zh-cn-messages/sql/03-zh-cn-messages.sql; otherwise run that 03 file, which includes these labels.
SET NAMES utf8mb4;
USE `service-system`;
INSERT INTO message (code, content, area) SELECT 'PagesFullWidth', JSON_OBJECT('en_US', 'Full width', 'zh_CN', '全宽'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesFullWidth') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '全宽') WHERE LOWER(code) = LOWER('PagesFullWidth') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesPointN', JSON_OBJECT('en_US', 'Point {number}', 'zh_CN', '要点 {number}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesPointN') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '要点 {number}') WHERE LOWER(code) = LOWER('PagesPointN') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesAddPoint', JSON_OBJECT('en_US', 'Add point', 'zh_CN', '添加要点'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesAddPoint') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '添加要点') WHERE LOWER(code) = LOWER('PagesAddPoint') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesFormHeading', JSON_OBJECT('en_US', 'Form heading', 'zh_CN', '表单标题'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesFormHeading') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '表单标题') WHERE LOWER(code) = LOWER('PagesFormHeading') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesFormText', JSON_OBJECT('en_US', 'Form text', 'zh_CN', '表单说明'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesFormText') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '表单说明') WHERE LOWER(code) = LOWER('PagesFormText') AND area = 'A';
@@ -0,0 +1,69 @@
# Tasks
## 1. Server
- [x] 1.1 services-counter `CmsBlock`: add `fullWidth` (Boolean), `formHeading` and `formText`. `CmsBlockValidator` HERO rules:
- allow `cards` on a HERO, 0 to 6 of them, each with a title that is required and at most 80 characters, and no icon or text;
- `formHeading` at most 80 characters and `formText` at most 200;
- refuse `formHeading` or `formText` without `eventUuid` (`PagesUnusedField`).
Verify: new validator tests fail first, then pass; `mvn -T 1C -pl solvway-services-counter verify`.
## 2. Portal
- [x] 2.1 `cmsPages.ts` types. In `CmsBlocks.tsx`:
- the HERO shows its points as a bulleted list;
- the form card shows `formHeading` and `formText`, editable in place;
- a full-width HERO renders outside the page width, with a larger serif heading, vertical centring and the lighter left-to-right shade;
- adjacent bleed blocks (HTML, or a full-width HERO) get no gap between them.
Verify: render tests fail first, then pass; vitest exit 0.
- [x] 2.2 `BlockFields.tsx`:
- the Hero gets a "Full width" switch, the points list (reusing the trust strip's item list), and the form heading and text fields, shown only when an event is picked;
- `INLINE.HERO` includes `formHeading`, `formText` and the points;
- add the labels to `defaultMessages.ts`, `zh_CN.seed.json` and `sql/01-hero-full-width-labels.sql`, and regenerate `local/seed/04-zh-cn-messages.sql`.
Verify: editor tests fail first, then pass; tsc and lint clean.
## 3. Verification
- [x] 3.1 Rebuild services-counter. Use Playwright on port 3001 to edit `/p/INS/hotel-technology` through the editor:
- turn on Full width;
- add the three INS points;
- set the form heading and text;
- publish the page.
Then check the published page at 1280 px and 390 px against the INS page, and check a save with 7 points shows the refusal on the canvas.
- [x] 3.2 Run the full portal vitest (exit 0), tsc, lint, Maven verify for services-counter, and `openspec validate add-hero-full-width --strict`.
- [x] 3.3 Add a release note to `docs/deployment.md` (label SQL).
## Notes (2026-12-04)
- **Red first:**
- the validator tests failed on points and the form heading;
- the render tests failed on full width, points, the card heading and the joins;
- the editor and company-switch tests failed;
- the frame floor, ask and answer tests failed.
- **Changed existing tests:**
- `CmsBlocks.html.test.tsx` "starts a header-less page flush at the top" now checks that the first block row has no top margin. It used to check for a `space-y` class, which is no longer how spacing works. It still asserts that the hidden title is outside the spacing.
- `frameHtml.test.ts` clamp test: the floor is now 20 px, per the modified "Custom HTML Frame Height" requirement. It also checks that 68 stays 68.
- **Live check** (port 3001, rebuilt counter), on `/p/INS/hotel-technology` through the editor:
- Full width switched on;
- three points and the form heading and text typed on the canvas;
- saved and published.
- **Published result at 1280 px:**
- the hero runs flush under the top bar and into the rest of the page;
- the serif headline is centred in the first screen;
- the points show in the accent colour, and the card has its heading.
- **Published result at 390 px:** the layout stacks, with the card below the text.
- **Fixes from the live check:**
- the text is centred in the opening height, not beside the long form;
- the frame floor is 20 px;
- the page asks frames for their height (both added to the spec).
- **Not reachable in the UI, covered by the validator tests:**
- 7 points, because Add point stops at 6;
- a form heading without a form, because No form clears it.
## Workflow follow-up
- Open a PR to `main` and merge it. Archive the change on its own branch, with its own PR.
+88
View File
@@ -0,0 +1,88 @@
# cluster-deployment Specification
## Purpose
Describe how Co-Lite is rolled out to Kubernetes from manifests in the repository, so that public exposure, secrets, image versions and rollback are fixed in reviewed files rather than typed by hand.
## Requirements
### Requirement: One manifest set deploys the whole system
The repository SHALL hold Kubernetes manifests that create a Deployment and a Service for each published image. The Service names and ports MUST be the ones the gateway, mobile-api and the portal already expect (`docs/deployment.md` section 1). Each Java service MUST have liveness and readiness probes on its actuator health endpoints. The admin portal MUST have a probe that needs no session.
#### Scenario: Apply brings every service up
- **GIVEN** a cluster where the Secrets, the mounted files, the database and the image pull secret already exist
- **WHEN** the deployer applies the `prod` overlay
- **THEN** a Deployment and a Service exist for all ten images under the expected names and ports
- **AND** every pod becomes ready
#### Scenario: Unhealthy pod gets no traffic
- **GIVEN** a Java service whose readiness endpoint reports down
- **WHEN** Kubernetes checks the pod
- **THEN** the pod is not ready and its Service sends it no requests
### Requirement: Only the portal and the WhatsApp webhook are public
The manifests SHALL route the public host, over TLS, to the admin-portal Service. They SHALL route exactly the path `/api/public/whatsapp/webhook` to the mobile-api Service. No other Service may be reachable from outside the cluster. The repository's manifest check MUST fail when a route targets any other Service or path.
#### Scenario: Gateway is not reachable from the internet
- **WHEN** the rendered `prod` manifests are checked
- **THEN** no route targets `api-gateway` or any `service-*`
- **AND** the only route to `mobile-api` matches exactly `/api/public/whatsapp/webhook`
#### Scenario: A new route is caught
- **GIVEN** a manifest change that adds a route to `api-gateway`
- **WHEN** the manifest check runs
- **THEN** it fails and names the route
### Requirement: Secrets never enter the repository
The manifests SHALL refer to Secrets and mounted files only by name. The repository MUST NOT hold any real secret value. Secret templates hold placeholders only. The script that creates the Secrets MUST read the values from files that git ignores.
#### Scenario: Rendered manifests hold no secret data
- **WHEN** the `prod` overlay is rendered
- **THEN** it contains no `Secret` object with data
- **AND** the manifest check fails if one appears
#### Scenario: Filled-in secret files cannot be committed
- **GIVEN** a deployer who fills in the secret files under the secrets folder
- **WHEN** they run `git status`
- **THEN** those files are ignored
### Requirement: Releases are pinned by commit and can be rolled back
The `prod` overlay SHALL pin every image to one commit SHA, never `latest`. Rolling back MUST be done by setting the previous SHA and applying again. The deployment docs MUST describe both steps. Before a real apply, a release check MUST refuse any cluster fact still left as a placeholder.
#### Scenario: latest is refused
- **GIVEN** a `prod` overlay where an image tag is `latest` or missing
- **WHEN** the manifest check runs
- **THEN** it fails and names the image
#### Scenario: Unfilled cluster fact refused before apply
- **GIVEN** a `prod` overlay that still holds a `<…>` placeholder, such as the MySQL host
- **WHEN** the deployer runs the release check
- **THEN** it fails and names each placeholder
#### Scenario: Roll back to the previous release
- **GIVEN** a release at SHA B that misbehaves, with SHA A deployed before it
- **WHEN** the deployer sets the overlay to SHA A and applies it
- **THEN** every Deployment rolls back to the SHA A images
### Requirement: Single-run jobs stay single
service-counter SHALL run as exactly one replica. It sends the daily follow-up summary, and two replicas would send it twice. The manifest check MUST fail when service-counter has more than one replica.
#### Scenario: Counter scaled by mistake
- **GIVEN** a manifest change that sets service-counter to two replicas
- **WHEN** the manifest check runs
- **THEN** it fails
+269 -9
View File
@@ -63,7 +63,7 @@ A page save SHALL be refused with the offending field path, writing nothing, whe
### Requirement: Block References Stay Inside The Company
A block's image SHALL be an image of the page's company, and a FORM block's event SHALL be an event of the page's company. Otherwise the save SHALL be refused on that field.
A block's image SHALL be an image of the page's company, and the event of a FORM block or of a HERO block that names one SHALL be an event of the page's company. Otherwise the save SHALL be refused on that field.
#### Scenario: Another company's event
@@ -71,6 +71,12 @@ A block's image SHALL be an image of the page's company, and a FORM block's even
- **WHEN** INS staff save a FORM block pointing at `CV Roadshow`
- **THEN** the save is refused on that block's event field
#### Scenario: Another company's event in a hero
- **GIVEN** event `CV Roadshow` belongs to CV
- **WHEN** INS staff save a HERO block whose event is `CV Roadshow`
- **THEN** the save is refused on that block's event field
### Requirement: Page Content Cannot Run Scripts
A button SHALL have both a label and a link or neither. The link SHALL start with a single `/`, `https://`, `mailto:`, `tel:`, or `#` plus a valid block link name. A save SHALL be refused when RICH_TEXT or IMAGE_TEXT HTML holds a `script` element, an `on*` attribute or a `javascript:` URL. The public page SHALL also sanitise that HTML against an allow-list. HTML blocks are exempt: they only run sealed.
@@ -193,7 +199,7 @@ Pages and page images SHALL follow the company scoping rules: staff see, edit an
### Requirement: The Pages List
`/pages` SHALL list the pages in scope with their title, public address, status and last update, with a search by title or slug and an Add page action. Each row SHALL open its editor. Pages SHALL appear in the sidebar for users with `BO_PAGES`.
`/pages` SHALL list the pages in scope with their title, public address, status, an "Unpublished changes" mark when a published page has a draft, and last update, with a search by title or slug and an Add page action. Each row SHALL open its editor and offer Duplicate. Pages SHALL appear in the sidebar for users with `BO_PAGES`.
#### Scenario: Draft in the list
@@ -201,9 +207,15 @@ Pages and page images SHALL follow the company scoping rules: staff see, edit an
- **WHEN** INS staff open `/pages`
- **THEN** its row shows status Draft and address `/p/INS/launch`
#### Scenario: Unpublished changes in the list
- **GIVEN** INS page `hotel` is published and has a saved draft
- **WHEN** INS staff open `/pages`
- **THEN** its row shows status Published and "Unpublished changes"
### Requirement: The Page Editor
The editor SHALL offer the title, a slug filled from the title until edited, a meta description with a 160-character counter, the status and the block list. Blocks SHALL be added, moved up or down and removed. A chosen image SHALL be uploaded only when the page is saved. A FORM block SHALL pick from the company's enabled events that have not ended.
At 1024 px and wider the editor SHALL be the on-page editor. Below 1024 px it SHALL be the form editor. Both SHALL offer the title, a slug filled from the title until edited, a meta description with a 160-character counter, the status, adding, moving and removing blocks, and images uploaded only on save. A FORM block SHALL pick from the company's enabled events that have not ended.
#### Scenario: Slug follows the title until edited
@@ -211,14 +223,25 @@ The editor SHALL offer the title, a slug filled from the title until edited, a m
- **WHEN** staff type the title "Hotel Technology"
- **THEN** the slug becomes `hotel-technology`
#### Scenario: Narrow window keeps the form
- **WHEN** staff open a page in a window 900 px wide
- **THEN** the form editor shows, with Preview
### Requirement: Saving And Deleting In The Editor
Server field errors SHALL show next to their fields, keeping all entered values. After a save the editor SHALL offer a link to view the page. Deleting a page SHALL ask first, and unsaved edits SHALL be guarded.
Server field errors SHALL show at their fields, keeping all entered values. After a save the editor SHALL offer a link to view the page. Deleting a page SHALL ask first. With unsaved edits, reloading, closing and following an in-app link SHALL ask first.
#### Scenario: Server error at its field
- **WHEN** staff save a HERO button link `javascript:alert(1)`
- **THEN** the error shows next to that button link and every entered value stays
- **THEN** the error shows at that button link and every entered value stays
#### Scenario: Leaving by an in-app link
- **GIVEN** staff changed a heading and did not save
- **WHEN** they click Pages in the menu
- **THEN** the editor asks before leaving, and Cancel keeps them on the page with the change
### Requirement: Custom HTML Runs Sealed
@@ -255,7 +278,7 @@ The public frame address SHALL be `/p/<company>/<slug>/frame/<block index>` and
### Requirement: Custom HTML Frame Height
The frame SHALL grow to fit its content, between 100 and 20000 pixels, using height reports sent by that frame only. Before the first report it SHALL be 600 pixels tall.
The frame SHALL grow or shrink to fit its content, between 20 and 20000 pixels, using height reports sent by that frame only. Before the first report it SHALL be 600 pixels tall. The frame SHALL report the height of its content, not of its own window, and SHALL report again whenever the page asks, which the page SHALL do once it listens and when the frame loads.
#### Scenario: A tall paste grows the frame
@@ -263,6 +286,12 @@ The frame SHALL grow to fit its content, between 100 and 20000 pixels, using hei
- **WHEN** a visitor opens the page
- **THEN** the frame is 3000 pixels tall and shows no inner scroll bar
#### Scenario: A short top bar shrinks the frame
- **GIVEN** a published HTML block holding only a 68 pixel top bar
- **WHEN** a visitor opens the page, even if the frame loaded before the page was ready
- **THEN** the frame is 68 pixels tall, with no blank space below the bar
#### Scenario: Another frame cannot resize it
- **WHEN** a different window posts a height report to the page
@@ -270,13 +299,20 @@ The frame SHALL grow to fit its content, between 100 and 20000 pixels, using hei
### Requirement: The Custom HTML Block In The Editor
The editor SHALL offer "Add Custom HTML", which adds an HTML block with a monospace text box, a 200000-character counter and a note that forms inside the pasted HTML do not send and the sign-up form block collects leads. The editor SHALL also offer a "hide page header" switch for the page.
The editor SHALL offer adding a Custom HTML block, edited in a monospace text box with a 200000-character counter and a note that forms inside it do not send. On the canvas the block SHALL show its last saved version as a sealed frame, marked "Save to update" while its HTML has unsaved edits. The editor SHALL offer a "hide page header" switch.
#### Scenario: Adding a Custom HTML block
- **WHEN** staff add a Custom HTML block and paste HTML into it
- **THEN** the block shows the pasted HTML, the character count and the note about forms
#### Scenario: Unsaved HTML on the canvas
- **GIVEN** a saved page with a Custom HTML block
- **WHEN** staff change its HTML in the panel
- **THEN** the canvas marks the block "Save to update"
- **AND** after Save the canvas shows the new HTML
#### Scenario: Hiding the header
- **WHEN** staff turn on "hide page header" and save
@@ -406,10 +442,234 @@ A HERO block MAY have no image; it then shows its heading, text and button on it
### Requirement: New Sections In The Editor
The page editor SHALL offer adding FEATURES, STEPS, TRUST and CTA blocks, editing their fields, adding, removing and reordering cards, and choosing any block's look. Refusals SHALL show at the field they name, including card fields.
Both editors SHALL offer adding FEATURES, STEPS, TRUST and CTA blocks, editing their fields, adding, removing and reordering cards, and choosing any block's look. Refusals SHALL show at the field they name, including card fields.
#### Scenario: A refused card title shows at its field
- **GIVEN** staff editing a page with a FEATURES block
- **WHEN** the save is refused on field `blocks[0].cards[1].title`
- **THEN** the message shows under the second card's title field
- **THEN** the message shows at the second card's title field
### Requirement: Published Pages Keep A Separate Draft
Saving a published page with status Published SHALL store the content as the page's draft, checked by the same rules as any save, and SHALL NOT change what visitors see. Saving a published page with status Draft SHALL unpublish it, write the content to the page and drop any draft. A page that is not published SHALL save directly, as before. The staff preview and the editor SHALL show the draft when there is one.
#### Scenario: Editing a live page does not change it for visitors
- **GIVEN** INS page `hotel` is published with heading "Hotel day"
- **WHEN** staff change the heading to "Hotel week" and save
- **THEN** visitors still see "Hotel day"
- **AND** the editor and the staff preview show "Hotel week"
#### Scenario: Unpublishing drops the draft
- **GIVEN** a published page with a draft
- **WHEN** staff choose status Draft and save
- **THEN** the page is a draft with the saved content and no separate draft
### Requirement: Publish And Discard Changes
Publishing a page's changes SHALL check its draft again by the same rules, including a unique slug, then make it the page's content and drop the draft. A refusal SHALL show at its field and change nothing. Discarding changes SHALL ask first, then drop the draft so the editor shows the published content again. Both SHALL be limited to pages in the caller's company scope.
#### Scenario: Publish changes
- **GIVEN** published page `hotel` has a draft with heading "Hotel week"
- **WHEN** staff press Publish changes
- **THEN** visitors see "Hotel week" and the page has no draft
#### Scenario: Publish refused for a taken slug
- **GIVEN** a draft with slug `launch` and another page published with slug `launch` since
- **WHEN** staff press Publish changes
- **THEN** the publish is refused on field `slug` and visitors still see the old content
#### Scenario: Discard changes
- **GIVEN** published page `hotel` has a draft
- **WHEN** staff press Discard changes and confirm
- **THEN** the draft is gone and the editor shows the published content
#### Scenario: Another company's page
- **WHEN** CV staff ask to publish INS page `hotel`
- **THEN** the request is answered "not found" and nothing changes
### Requirement: Starter Templates
New page SHALL first offer Blank, Event sign-up and Service showcase. A template SHALL fill the editor with its sections, placeholder text, a sign-up form with link name `signup` and no event, and buttons linking to `#signup`; nothing is stored until staff save. Every template's sections SHALL pass the server's block rules once an event is chosen.
#### Scenario: Start from the event template
- **WHEN** staff choose New page, then Event sign-up
- **THEN** the editor shows a hero, trust strip, feature cards, steps, FAQ and a sign-up form, filled with placeholder text
- **AND** saving it without choosing the form's event is refused on that event field
### Requirement: Duplicate A Page
Duplicate SHALL open the editor with a copy of the page's current content (its draft when there is one), as a new unsaved draft page of the same company titled "<title> (copy)" with slug "<slug>-copy". Nothing SHALL be stored until staff save.
#### Scenario: Duplicate last event's page
- **GIVEN** INS page `hotel` titled "Hotel day"
- **WHEN** staff press Duplicate on it and save
- **THEN** a new draft INS page `hotel-copy` titled "Hotel day (copy)" exists with the same sections
### Requirement: The Page Canvas
The on-page editor SHALL show the page on a canvas, rendered as visitors see it, with a Desktop view (1280 px wide, scaled to fit) and a Phone view (390 px wide). Changes SHALL show on the canvas as they are made, before saving. Links and buttons on the canvas SHALL NOT navigate, and the sign-up form SHALL show its preview note.
#### Scenario: Phone view uses the phone layout
- **GIVEN** a page with a FEATURES block of three cards
- **WHEN** staff switch to Phone
- **THEN** the cards stack in one column on the canvas
#### Scenario: A change shows before saving
- **WHEN** staff change a FEATURES card title in the side panel
- **THEN** the canvas shows the new title at once
### Requirement: Edit Text On The Page
Clicking a heading, short text, button label, card title or text, or FAQ question or answer on the canvas SHALL edit it in place as plain text, with the server's length limit shown when close. Rich text SHALL be edited in place with bold, italic, link, lists and alignment, and links SHALL follow the page link rule. An empty field SHALL show a faded cue naming it, and empty rich text SHALL keep room to click into. Clicking an image spot SHALL open the file picker.
#### Scenario: Edit a heading in place
- **WHEN** staff click the hero heading on the canvas and type "Hotel week"
- **THEN** the canvas and the side panel show "Hotel week"
#### Scenario: An unsafe link is refused in rich text
- **WHEN** staff add the link `javascript:alert(1)` in a Text block on the canvas
- **THEN** the link is not added and the toolbar says why
### Requirement: Section Selection And Actions
Clicking a section on the canvas SHALL select it, outline it and show its settings in the side panel. With none selected, the panel SHALL show the page settings. A selected section SHALL offer drag, up, down, duplicate and delete. "Add section" between sections and at the end SHALL offer every block type. Up and down SHALL work from the keyboard. A section that is added, duplicated or moved SHALL be brought into view on the canvas.
#### Scenario: Duplicate a section
- **WHEN** staff select the second section and press Duplicate
- **THEN** a copy appears as the third section and is selected
#### Scenario: Add a section between two
- **WHEN** staff press Add section between the first and second sections and choose Steps
- **THEN** a Steps section appears second and is selected
#### Scenario: Add a section from the side panel
- **GIVEN** the canvas shows the top of a long page
- **WHEN** staff press Add Text in the side panel
- **THEN** the canvas scrolls to the new Text section at the end, which shows a faded "Content" cue to type into
### Requirement: Undo And Redo
The on-page editor SHALL undo and redo page changes, up to 50 steps, by buttons and by Ctrl+Z and Ctrl+Shift+Z. The keys SHALL work wherever focus is in the editor, including after the focused control is removed or disabled, except inside a field outside the editor. Typing in one field SHALL be one step. Saving SHALL NOT clear the history.
#### Scenario: Undo a delete
- **GIVEN** staff deleted the FAQ section
- **WHEN** they press Ctrl+Z
- **THEN** the FAQ section is back in its place with its content
### Requirement: Refusals On The Canvas
When a save or publish is refused on a block field, the editor SHALL select that block, outline it, scroll it into view and show the message at the field in the side panel. A refusal on a page field SHALL show in the page settings.
#### Scenario: A form without an event
- **GIVEN** a page from the Event sign-up template
- **WHEN** staff save without choosing the form's event
- **THEN** the form section is selected and outlined and the panel shows the message at the Event field
### Requirement: Hero With A Sign-Up Form
A HERO block MAY name an event. When it does, the hero SHALL show Co-Lite's sign-up form for that event in a card beside its heading, text and button on wide screens, and below them on narrow screens. The hero's form SHALL follow every rule of the FORM block (see "The Form Block Registers For An Event" and "The Form Block Closes With Its Event"). A HERO block without an event SHALL show no form.
#### Scenario: Sign up from the hero
- **GIVEN** page `/p/INS/hotel-technology` has a HERO block whose event is `INS website enquiries`
- **WHEN** a new visitor submits the form in the hero from a URL with `utm_source=facebook`
- **THEN** a new lead and an event lead with source Web page, no salesperson and UTM source `facebook` are created
#### Scenario: Hero form closes with its event
- **GIVEN** the HERO block's event ended yesterday
- **WHEN** a visitor opens the page
- **THEN** the hero still shows its heading and text, and its form area says sign-up is closed
#### Scenario: Hero without an event
- **WHEN** a visitor opens a page whose HERO block names no event
- **THEN** the hero shows no form
- **AND** a submit addressed to that block is refused as not found
#### Scenario: Pick the hero's event in the editor
- **GIVEN** staff editing a page with a HERO block
- **WHEN** they pick `INS website enquiries` under the hero's sign-up form setting
- **THEN** the canvas shows the form card beside the hero text
- **AND** choosing "No form" removes it
### Requirement: Full-Width Hero
A HERO block MAY be marked full width. A full-width hero SHALL span the whole window with square corners, show its heading larger and centred top to bottom in the hero's opening height (not beside a long form), and use a shade that is darker on the text side than on the far side. A hero that is not marked full width SHALL look as it did before. The server SHALL refuse a `fullWidth` value that is not true or false.
#### Scenario: Hero runs edge to edge under a Custom HTML top bar
- **GIVEN** page `/p/INS/hotel-technology` with a Custom HTML top bar followed by a full-width HERO with an image and an event
- **WHEN** a visitor opens the page in a 1280 px window
- **THEN** the hero spans the full window width
- **AND** the form card sits beside the heading
#### Scenario: Existing hero unchanged
- **WHEN** a visitor opens a page whose HERO block is not marked full width
- **THEN** the hero sits inside the page width with rounded corners, as before
#### Scenario: Turn on full width in the editor
- **GIVEN** staff editing a page with a HERO block
- **WHEN** they switch on "Full width" in the hero's settings
- **THEN** the canvas shows the hero across the full width
### Requirement: Full-Width Blocks Join Without Gaps
A full-width HERO and a Custom HTML block next to each other SHALL join with no gap between them, and so SHALL two Custom HTML blocks next to each other. Other blocks SHALL keep their usual spacing.
#### Scenario: Top bar runs straight into the hero
- **GIVEN** a Custom HTML top bar followed by a full-width HERO
- **WHEN** a visitor opens the page
- **THEN** the hero starts directly under the top bar, with no gap
### Requirement: Hero Points
A HERO block MAY carry up to 6 points, each a non-empty title of at most 80 characters, with no icon and no text. The hero SHALL show its points as a bulleted list under its text. The server SHALL refuse more than 6 points, an empty or over-long point, and a point with an icon or text, naming the field.
#### Scenario: Points under the hero text
- **GIVEN** a HERO block with points "One accountable partner instead of five vendors" and "Local support team in Malaysia"
- **WHEN** a visitor opens the page
- **THEN** both points show as a bulleted list under the hero text
#### Scenario: Too many points refused
- **WHEN** staff save a HERO block with 7 points
- **THEN** the save is refused at `blocks[n].cards`
### Requirement: Hero Form Heading
A HERO block with an event MAY carry a form heading of at most 80 characters and a form text of at most 200 characters. The hero SHALL show them at the top of its form card, above the form. The server SHALL refuse either on a hero without an event. On the canvas, staff SHALL be able to type both in place.
#### Scenario: Card shows its heading
- **GIVEN** a HERO block with an event, form heading "Get a free consultation" and form text "Tell us about your property. It takes under a minute."
- **WHEN** a visitor opens the page
- **THEN** the form card starts with that heading and text, followed by the form
#### Scenario: Form heading without a form refused
- **WHEN** staff save a HERO block with a form heading and no event
- **THEN** the save is refused at `blocks[n].formHeading`
@@ -6,6 +6,7 @@ import { BLOCK_LABELS, ICONS, LOOKS, imageSrc, type CmsBlock, type CmsCard, type
import { Button } from "@/app/components/ui/button";
import { Input } from "@/app/components/ui/input";
import { Label } from "@/app/components/ui/label";
import { Switch } from "@/app/components/ui/switch";
import { Textarea } from "@/app/components/ui/textarea";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import { RichTextEditor } from "./RichTextEditor";
@@ -14,7 +15,7 @@ import { RichTextEditor } from "./RichTextEditor";
/** Field paths (relative to the block) each type shows inline; any other error shows at the block's top. Every type also shows "anchor". */
const INLINE: Record<string, string[]> = {
HERO: ["imageId", "heading", "text", "buttonLabel", "buttonUrl"],
HERO: ["imageId", "heading", "text", "buttonLabel", "buttonUrl", "eventUuid", "fullWidth", "formHeading", "formText", "cards"],
RICH_TEXT: ["html"],
IMAGE_TEXT: ["imageId", "imagePosition", "heading", "html", "buttonLabel", "buttonUrl"],
FAQ: ["heading", "items"],
@@ -34,10 +35,12 @@ const ICON_LABELS: Record<string, string> = {
"shield-check": "PagesIconShieldCheck", cloud: "PagesIconCloud", wrench: "PagesIconWrench", headset: "PagesIconHeadset",
users: "PagesIconUsers", calendar: "PagesIconCalendar", star: "PagesIconStar",
};
const CARD_KINDS: Record<string, { legend: string; add: string; icon: boolean; text: boolean; empty: CmsCard }> = {
FEATURES: { legend: "PagesCardN", add: "PagesAddCard", icon: true, text: true, empty: { icon: "star", title: "", text: "" } },
STEPS: { legend: "PagesStepN", add: "PagesAddStep", icon: false, text: true, empty: { title: "", text: "" } },
TRUST: { legend: "PagesItemN", add: "PagesAddItem", icon: false, text: false, empty: { title: "" } },
// add-hero-full-width: a hero's points are title-only cards, and it may have none.
const CARD_KINDS: Record<string, { legend: string; add: string; icon: boolean; text: boolean; min: number; empty: CmsCard }> = {
FEATURES: { legend: "PagesCardN", add: "PagesAddCard", icon: true, text: true, min: 2, empty: { icon: "star", title: "", text: "" } },
STEPS: { legend: "PagesStepN", add: "PagesAddStep", icon: false, text: true, min: 2, empty: { title: "", text: "" } },
TRUST: { legend: "PagesItemN", add: "PagesAddItem", icon: false, text: false, min: 2, empty: { title: "" } },
HERO: { legend: "PagesPointN", add: "PagesAddPoint", icon: false, text: false, min: 0, empty: { title: "" } },
};
const SELECT = "flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm disabled:cursor-not-allowed disabled:opacity-50";
@@ -83,7 +86,7 @@ export function BlockFields(props: {
const fid = (name: string) => `block-${id}-${name}`;
const topErrors = Object.entries(errors).filter(([path]) => path !== "anchor" && path !== "look" && !INLINE[block.type]?.includes(path) && !LISTED.test(path));
const text = (name: "heading" | "text" | "buttonLabel" | "buttonUrl" | "anchor", labelCode: string) => (
const text = (name: "heading" | "text" | "buttonLabel" | "buttonUrl" | "anchor" | "formHeading" | "formText", labelCode: string) => (
<Field id={fid(name)} label={t(labelCode)} error={errors[name]}>
<Input id={fid(name)} value={block[name] ?? ""} disabled={saving} aria-invalid={!!errors[name]} onChange={(e) => set({ [name]: e.target.value })} />
</Field>
@@ -96,6 +99,20 @@ export function BlockFields(props: {
);
const preview = pendingImage?.preview ?? (block.imageId ? imageSrc(block.imageId) : undefined);
// The FORM block's event, and the hero's optional sign-up form (add-hero-signup-form): the same picker and hint.
const eventPicker = (labelCode: string, emptyCode: string) => (
<Field id={fid("event")} label={t(labelCode)} error={errors.eventUuid}>
<select id={fid("event")} className={SELECT} value={block.eventUuid ?? ""} disabled={saving} aria-invalid={!!errors.eventUuid}
onChange={(e) => set(e.target.value ? { eventUuid: e.target.value } : { eventUuid: null, formHeading: undefined, formText: undefined })}>
<option value="">{t(emptyCode)}</option>
{events.map((ev) => <option key={ev.uuid} value={ev.uuid}>{ev.name}</option>)}
{block.eventUuid && !events.some((ev) => ev.uuid === block.eventUuid) ? (
<option value={block.eventUuid}>{t("PagesUnavailableEvent")}</option>
) : null}
</select>
<p className="text-xs text-muted-foreground">{t("PagesFormEventHint")}</p>
</Field>
);
const image = (
<Field id={fid("image")} label={t("PagesImage")} error={errors.imageId}>
<Input
@@ -126,8 +143,8 @@ export function BlockFields(props: {
<>
{cards.map((card, i) => {
const err = (f: string) => errors[`cards[${i}].${f}`];
const cardField = (f: "title" | "text", labelCode: string, multiline: boolean) => (
<Field id={fid(`c${i}${f}`)} label={t(labelCode)} error={err(f)}>
const cardField = (f: "title" | "text", label: string, multiline: boolean) => (
<Field id={fid(`c${i}${f}`)} label={label} error={err(f)}>
{multiline
? <Textarea id={fid(`c${i}${f}`)} rows={2} value={card[f] ?? ""} disabled={saving} aria-invalid={!!err(f)}
onChange={(e) => setCards(cards.map((c, j) => (j === i ? { ...c, [f]: e.target.value } : c)))} />
@@ -146,12 +163,12 @@ export function BlockFields(props: {
</select>
</Field>
) : null}
{cardField("title", "PagesCardTitle", false)}
{kind.text ? cardField("text", "PagesCardText", true) : null}
{cardField("title", kind.min ? t("PagesCardTitle") : t(kind.legend, { number: i + 1 }), false)}
{kind.text ? cardField("text", t("PagesCardText"), true) : null}
<div className="flex flex-wrap gap-1">
<Button type="button" variant="ghost" size="sm" disabled={saving || i === 0} onClick={() => moveCard(i, -1)}>{t("PagesMoveUp")}</Button>
<Button type="button" variant="ghost" size="sm" disabled={saving || i === cards.length - 1} onClick={() => moveCard(i, 1)}>{t("PagesMoveDown")}</Button>
<Button type="button" variant="ghost" size="sm" disabled={saving || cards.length <= 2} onClick={() => setCards(cards.filter((_, j) => j !== i))}>{t("PagesRemoveCard")}</Button>
<Button type="button" variant="ghost" size="sm" disabled={saving || cards.length <= kind.min} onClick={() => setCards(cards.filter((_, j) => j !== i))}>{t("PagesRemoveCard")}</Button>
</div>
</fieldset>
);
@@ -190,6 +207,18 @@ export function BlockFields(props: {
{text("text", "PagesText")}
{text("buttonLabel", "PagesButtonLabel")}
{text("buttonUrl", "PagesButtonLink")}
<div className="flex items-center gap-2">
<Switch id={fid("fullWidth")} checked={!!block.fullWidth} disabled={saving} onCheckedChange={(on) => set({ fullWidth: on || undefined })} />
<Label htmlFor={fid("fullWidth")}>{t("PagesFullWidth")}</Label>
</div>
{cardList}
{eventPicker("PagesHeroForm", "PagesNoForm")}
{block.eventUuid ? (
<>
{text("formHeading", "PagesFormHeading")}
{text("formText", "PagesFormText")}
</>
) : null}
</>
)}
@@ -249,17 +278,7 @@ export function BlockFields(props: {
{block.type === "FORM" && (
<>
{text("heading", "PagesHeading")}
<Field id={fid("event")} label={t("PagesFormEvent")} error={errors.eventUuid}>
<select id={fid("event")} className={SELECT} value={block.eventUuid ?? ""} disabled={saving} aria-invalid={!!errors.eventUuid}
onChange={(e) => set({ eventUuid: e.target.value || null })}>
<option value="">{t("PagesChooseEvent")}</option>
{events.map((ev) => <option key={ev.uuid} value={ev.uuid}>{ev.name}</option>)}
{block.eventUuid && !events.some((ev) => ev.uuid === block.eventUuid) ? (
<option value={block.eventUuid}>{t("PagesUnavailableEvent")}</option>
) : null}
</select>
<p className="text-xs text-muted-foreground">{t("PagesFormEventHint")}</p>
</Field>
{eventPicker("PagesFormEvent", "PagesChooseEvent")}
</>
)}
@@ -0,0 +1,28 @@
import { render, waitFor, within } from "@testing-library/react";
import { describe, it, expect } from "vitest";
import { CanvasFrame } from "./CanvasFrame";
// add-page-visual-editor: the canvas renders into its own blank document, with the editor's styles and theme.
const frame = () => document.querySelector("iframe") as HTMLIFrameElement;
describe("CanvasFrame", () => {
it("renders its children inside the frame's document, at the given size, carrying the editor's styles and theme", async () => {
const style = document.head.appendChild(document.createElement("style"));
style.textContent = ".x{color:red}";
document.documentElement.classList.add("dark");
try {
render(<CanvasFrame width={390} height={700} title="Canvas"><p>On the canvas</p></CanvasFrame>);
expect(frame()).toHaveStyle({ width: "390px", height: "700px" });
const inner = () => frame().contentDocument!;
await waitFor(() => expect(within(inner().body).getByText("On the canvas")).toBeInTheDocument());
expect(document.body).not.toHaveTextContent("On the canvas");
expect(inner().documentElement).toHaveClass("dark");
expect(inner().head.querySelector("style")?.textContent).toBe(".x{color:red}");
document.documentElement.classList.remove("dark");
await waitFor(() => expect(inner().documentElement).not.toHaveClass("dark"));
} finally {
style.remove();
document.documentElement.classList.remove("dark");
}
});
});
@@ -0,0 +1,51 @@
"use client";
import { useEffect, useRef, useState, type ReactNode } from "react";
import { createPortal } from "react-dom";
const BLANK = "<!doctype html><html><head></head><body></body></html>";
/** Copies the editor's stylesheets and <html> class, style and lang into the frame and keeps them in step; returns the stop. */
function mirror(doc: Document): () => void {
const syncHead = () => doc.head.replaceChildren(...[...document.head.querySelectorAll('link[rel="stylesheet"], style')].map((n) => n.cloneNode(true)));
const syncRoot = () => {
const root = document.documentElement;
doc.documentElement.className = root.className;
doc.documentElement.setAttribute("style", root.getAttribute("style") ?? "");
doc.documentElement.lang = root.lang;
};
syncHead();
syncRoot();
doc.body.className = document.body.className;
doc.body.style.margin = "0";
const heads = new MutationObserver(syncHead);
heads.observe(document.head, { childList: true, subtree: true, characterData: true });
const roots = new MutationObserver(syncRoot);
roots.observe(document.documentElement, { attributes: true, attributeFilter: ["class", "style", "lang"] });
return () => { heads.disconnect(); roots.disconnect(); };
}
/**
* A blank same-origin frame that its children render into by portal (add-page-visual-editor, design Decision 1).
* The frame is a device screen: its own viewport, so the page's breakpoints follow its width, and it scrolls inside.
*/
export function CanvasFrame({ width, height, title, children }: { width: number; height: number; title: string; children: ReactNode }) {
// A container in the loaded blank document, which React removes the portal from cleanly when the frame goes.
// srcDoc plus onLoad, so no browser swaps the document out after the first render.
const [root, setRoot] = useState<HTMLElement | null>(null);
const stop = useRef<() => void>(undefined);
useEffect(() => () => stop.current?.(), []);
return (
<>
<iframe title={title} srcDoc={BLANK} className="block border-0 bg-background" style={{ width, height }}
onLoad={(e) => {
const doc = e.currentTarget.contentDocument;
if (!doc) return;
stop.current?.();
stop.current = mirror(doc);
setRoot(doc.body.appendChild(doc.createElement("div")));
}} />
{root ? createPortal(children, root) : null}
</>
);
}
@@ -0,0 +1,122 @@
import { fireEvent, render, screen, within } from "@testing-library/react";
import { describe, it, expect, vi } from "vitest";
import { LandingPage, type PublicBlock } from "./CmsBlocks";
import { setField, type PageEdit } from "./CmsEdit";
// add-page-visual-editor: the page in edit mode. Text edits in place, sections select, images open the picker, and
// nothing navigates. Without `edit` the page renders exactly as before (CmsBlocks*.test.tsx).
const company = { code: "INS", name: "INS Sdn Bhd" };
const page = (blocks: PublicBlock[]) => ({ slug: "hotel", title: "Hotel day", blocks });
function editor(overrides: Partial<PageEdit> = {}): PageEdit {
return {
selected: null, select: vi.fn(), text: vi.fn(), html: vi.fn(), image: vi.fn(),
preview: () => undefined, stale: () => false, frameVersion: 0, chrome: () => null, ...overrides,
};
}
const typeInto = (el: HTMLElement, value: string) => { el.textContent = value; fireEvent.input(el); };
describe("LandingPage in edit mode", () => {
it("edits a heading, a card title and a FAQ answer in place as plain text", () => {
const edit = editor();
render(<LandingPage company={company} page={page([
{ type: "HERO", heading: "Hotel week" },
{ type: "FEATURES", heading: "Why", cards: [{ title: "A" }, { title: "B" }] },
{ type: "FAQ", items: [{ question: "Q", answer: "A1" }] },
])} edit={edit} preview />);
const heading = screen.getAllByRole("textbox", { name: "Heading" })[0];
expect(heading).toHaveAttribute("contenteditable", "plaintext-only");
expect(heading).toHaveTextContent("Hotel week");
typeInto(heading, "Hotel month");
expect(edit.text).toHaveBeenLastCalledWith(0, "heading", "Hotel month");
typeInto(screen.getAllByRole("textbox", { name: "Title" })[1], "Second");
expect(edit.text).toHaveBeenLastCalledWith(1, "cards.1.title", "Second");
typeInto(screen.getByRole("textbox", { name: "Answer 1" }), "Yes\nno");
expect(edit.text).toHaveBeenLastCalledWith(2, "items.0.answer", "Yes\nno");
});
it("offers an empty heading as a spot to type, and shows the limit once close to it", () => {
render(<LandingPage company={company} page={page([{ type: "CTA", heading: "x".repeat(100) }, { type: "FEATURES", cards: [{ title: "A" }, { title: "B" }] }])} edit={editor()} preview />);
expect(screen.getByText("100/120")).toBeInTheDocument();
expect(screen.getAllByRole("textbox", { name: "Heading" })[1]).toHaveTextContent("");
});
it("selects a section on click, outlines the selected one, and draws the editor's tools in it", () => {
const edit = editor({ selected: 1, chrome: (i) => <span>tools {i}</span> });
render(<LandingPage company={company} page={page([{ type: "CTA", heading: "One" }, { type: "CTA", heading: "Two" }])} edit={edit} preview />);
const sections = document.querySelectorAll("[data-index]");
expect([...sections].map((s) => s.getAttribute("data-index"))).toEqual(["0", "1"]);
expect(sections[1]).toHaveAttribute("data-selected", "true");
expect(sections[0]).not.toHaveAttribute("data-selected");
expect(within(sections[1] as HTMLElement).getByText("tools 1")).toBeInTheDocument();
fireEvent.click(sections[0]);
expect(edit.select).toHaveBeenCalledWith(0);
});
it("keeps links and buttons from navigating, and edits a button's label", () => {
const edit = editor();
render(<LandingPage company={company} page={page([{ type: "CTA", heading: "Go", buttonLabel: "Join", buttonUrl: "https://example.com" }])} edit={edit} preview />);
const label = screen.getByRole("textbox", { name: "Button label" });
const link = label.closest("a")!;
expect(fireEvent.click(link)).toBe(false); // default prevented
typeInto(label, "Join now");
expect(edit.text).toHaveBeenLastCalledWith(0, "buttonLabel", "Join now");
});
it("opens the picker from an image spot and shows a chosen image before it is saved", () => {
const edit = editor({ preview: (i) => (i === 0 ? "data:image/png;base64,AAAA" : undefined) });
render(<LandingPage company={company} page={page([{ type: "IMAGE_TEXT", heading: "Pic", imageId: 4 }, { type: "IMAGE_TEXT", heading: "None" }])} edit={edit} preview />);
const spots = screen.getAllByRole("button", { name: "Image" });
expect(spots).toHaveLength(2);
expect(spots[0].querySelector("img")).toHaveAttribute("src", "data:image/png;base64,AAAA");
fireEvent.click(spots[1]);
expect(edit.image).toHaveBeenCalledWith(1);
});
it("shows a Custom HTML block's saved version, selectable, marked while its HTML has unsaved edits", () => {
const edit = editor({ stale: (i) => i === 0, frameVersion: 3 });
render(<LandingPage company={company} page={page([{ type: "HTML", html: "<p>x</p>" }])} edit={edit} preview frameBase="/pages/5/preview/frame" />);
expect(document.querySelector("iframe")).toHaveAttribute("src", "/pages/5/preview/frame/0?v=3");
expect(screen.getByText("Save to update")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Custom HTML" }));
expect(edit.select).toHaveBeenCalledWith(0);
});
it("edits rich text in place in the page's own style, for a Text block and an image-and-text block", async () => {
render(<LandingPage company={company} page={page([{ type: "RICH_TEXT", html: "<p>Body copy</p>" }, { type: "IMAGE_TEXT", heading: "Pic", html: "" }])} edit={editor()} preview />);
const boxes = await screen.findAllByRole("textbox", { name: "Content" });
expect(boxes).toHaveLength(2);
expect(boxes[0]).toHaveAttribute("contenteditable", "true");
expect(boxes[0]).toHaveTextContent("Body copy");
expect(screen.getAllByText("Body copy")).toHaveLength(1);
});
it("offers empty rich text as a spot to type: a faded cue that goes once there is text", async () => {
const { rerender } = render(<LandingPage company={company} page={page([{ type: "RICH_TEXT", html: "" }])} edit={editor()} preview />);
await screen.findByRole("textbox", { name: "Content" });
const cue = screen.getByText("Content", { selector: "p[aria-hidden]" });
expect(cue.parentElement!.className).toContain("[&_.ProseMirror]:min-h-24");
rerender(<LandingPage company={company} page={page([{ type: "RICH_TEXT", html: "<p>Hi</p>" }])} edit={editor()} preview />);
expect(screen.queryByText("Content", { selector: "p[aria-hidden]" })).not.toBeInTheDocument();
});
it("renders no editing without edit mode", () => {
render(<LandingPage company={company} page={page([{ type: "HERO", heading: "Hotel week" }, { type: "IMAGE_TEXT", heading: "Pic", imageId: 4 }])} />);
expect(document.querySelector("[contenteditable]")).toBeNull();
expect(document.querySelector("[data-index]")).toBeNull();
expect(screen.queryByRole("button")).toBeNull();
expect(screen.getByRole("heading", { level: 2, name: "Hotel week" })).toBeInTheDocument();
});
});
describe("setField", () => {
it("sets a top-level field or one inside a card or question, leaving the rest", () => {
const block = { type: "FEATURES" as const, heading: "H", cards: [{ title: "A", text: "a" }, { title: "B" }] };
expect(setField(block, "heading", "New")).toEqual({ ...block, heading: "New" });
expect(setField(block, "cards.1.title", "C").cards).toEqual([{ title: "A", text: "a" }, { title: "C" }]);
expect(block.cards[1].title).toBe("B");
expect(setField({ type: "FAQ", items: [{ question: "Q", answer: "A" }] }, "items.0.answer", "Z").items).toEqual([{ question: "Q", answer: "Z" }]);
});
});
@@ -1,5 +1,5 @@
import { act, render, screen } from "@testing-library/react";
import { describe, it, expect, vi } from "vitest";
import { describe, it, expect, onTestFinished, vi } from "vitest";
import { LandingPage, type PublicBlock } from "./CmsBlocks";
import { FRAME_SANDBOX } from "@/app/lib/frameHtml";
@@ -58,6 +58,29 @@ describe("LandingPage: Custom HTML", () => {
expect(frame().style.height).toBe("2400px");
});
// add-hero-full-width: the frame's first report can arrive before the page listens, so the page asks once it does.
it("asks its frame for a height report once it listens, and again when the frame loads", () => {
const sealed = { postMessage: vi.fn() };
const getter = vi.spyOn(HTMLIFrameElement.prototype, "contentWindow", "get").mockReturnValue(sealed as unknown as Window);
onTestFinished(() => getter.mockRestore());
render(<LandingPage company={company} page={page([HTML])} />);
expect(sealed.postMessage).toHaveBeenCalledWith({ type: "colite-frame-ask" }, "*");
sealed.postMessage.mockClear();
act(() => { frame().dispatchEvent(new Event("load")); });
expect(sealed.postMessage).toHaveBeenCalledWith({ type: "colite-frame-ask" }, "*");
});
it("grows inside another document too: it listens on its own document's window (add-page-visual-editor)", () => {
const host = document.createElement("iframe");
document.body.appendChild(host);
onTestFinished(() => host.remove());
const inner = host.contentDocument!;
render(<LandingPage company={company} page={page([HTML])} />, { container: inner.body.appendChild(inner.createElement("div")) });
const sealed = inner.querySelector("iframe") as HTMLIFrameElement;
act(() => { host.contentWindow!.dispatchEvent(new MessageEvent("message", { data: { type: "colite-frame-height", height: 2400 }, source: sealed.contentWindow })); });
expect(sealed.style.height).toBe("2400px");
});
it("hides the company header and shows the title to screen readers only when the page says so", () => {
render(<LandingPage company={company} page={page([HTML], true)} />);
expect(screen.queryByRole("img", { name: "INS Sdn Bhd" })).not.toBeInTheDocument();
@@ -69,6 +92,7 @@ describe("LandingPage: Custom HTML", () => {
render(<LandingPage company={company} page={page([HTML], true)} />);
const title = screen.getByRole("heading", { level: 1, name: "Hotel day" });
expect(title.parentElement!.className).not.toMatch(/space-y/);
expect(frame().parentElement!.className).toMatch(/space-y/);
// add-hero-full-width: spacing is a top margin on each block row after the first, so the first row has none.
expect(frame().closest("main > div > div")).not.toHaveClass("mt-10");
});
});
@@ -1,4 +1,4 @@
import { render, screen } from "@testing-library/react";
import { render, screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect, vi, beforeEach } from "vitest";
import { LandingPage, type PublicBlock } from "./CmsBlocks";
@@ -70,6 +70,77 @@ describe("LandingPage", () => {
expect(JSON.parse(String((init as RequestInit).body))).toMatchObject({ name: "Tan", utmSource: "fb", utmMedium: "cpc", utmCampaign: "jan" });
expect(await screen.findByText("Sign-up is closed.")).toBeInTheDocument();
});
// add-hero-signup-form: a hero with an event carries the sign-up form beside its text.
it("a hero with an event shows the sign-up form inside the hero and posts to the hero's block", async () => {
window.history.replaceState(null, "", "/p/INS/hotel?utm_source=fb");
const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(new Response(JSON.stringify({ code: "FORM_CLOSED" }), { status: 409 }));
const user = userEvent.setup();
render(<LandingPage company={company} page={page([{ type: "HERO", heading: "One partner", eventUuid: "77", form: info }])} />);
const hero = screen.getByRole("heading", { name: "One partner" }).closest("section")!;
expect(hero).toContainElement(screen.getByLabelText("Your name"));
await user.type(screen.getByLabelText("Your name"), "Tan");
await user.type(screen.getByLabelText("Mobile number"), "0125550101");
await user.click(screen.getByRole("checkbox"));
await user.click(screen.getByRole("button", { name: "Register" }));
expect(fetchMock.mock.calls[0][0]).toBe("/api/public/pages/INS/hotel/form/0");
});
it("a hero whose form closed keeps its text and says so; a hero without an event has no form", () => {
const { unmount } = render(<LandingPage company={company} page={page([{ type: "HERO", heading: "One partner", eventUuid: "77", closed: true }])} />);
const hero = screen.getByRole("heading", { name: "One partner" }).closest("section")!;
expect(hero).toHaveTextContent("Sign-up is closed.");
unmount();
render(<LandingPage company={company} page={page([{ type: "HERO", heading: "Plain" }])} />);
expect(screen.queryByText("Sign-up is closed.")).not.toBeInTheDocument();
expect(screen.queryByLabelText("Your name")).not.toBeInTheDocument();
});
it("the preview of a hero with an event shows the form's note in the hero", () => {
render(<LandingPage company={company} page={page([{ type: "HERO", heading: "One partner", eventUuid: "77" }])} preview />);
expect(screen.getByRole("heading", { name: "One partner" }).closest("section"))
.toHaveTextContent("The sign-up form shows here on the published page.");
});
});
// add-hero-full-width: edge-to-edge hero, points, the form card's heading, and flush full-width neighbours.
describe("LandingPage full-width hero", () => {
const ins = { type: "HERO" as const, heading: "One partner", fullWidth: true, eventUuid: "77", closed: true,
cards: [{ title: "One accountable partner" }, { title: "Local support team in Malaysia" }],
formHeading: "Get a free consultation", formText: "Tell us about your property." };
it("runs outside the page width with square corners; a plain hero stays boxed in the page width", () => {
render(<LandingPage company={company} page={page([ins, { type: "HERO", heading: "Boxed" }])} />);
const wide = screen.getByRole("heading", { name: "One partner" }).closest("section")!;
expect(wide.closest(".max-w-5xl")).toBeNull();
expect(wide).not.toHaveClass("rounded-lg");
const boxed = screen.getByRole("heading", { name: "Boxed" }).closest("section")!;
expect(boxed.closest(".max-w-5xl")).not.toBeNull();
expect(boxed).toHaveClass("rounded-lg");
});
it("shows its points as a list under the text", () => {
render(<LandingPage company={company} page={page([ins])} />);
const hero = screen.getByRole("heading", { name: "One partner" }).closest("section")!;
const items = within(hero).getAllByRole("listitem");
expect(items.map((li) => li.textContent)).toEqual(["One accountable partner", "Local support team in Malaysia"]);
});
it("starts the form card with its heading and text", () => {
render(<LandingPage company={company} page={page([ins])} />);
const title = screen.getByRole("heading", { name: "Get a free consultation" });
const card = title.parentElement!.parentElement!;
expect(card).toHaveTextContent(/^Get a free consultation\s*Tell us about your property\./);
expect(card).toHaveTextContent("Sign-up is closed.");
});
it("joins a Custom HTML block and a full-width hero with no gap; other blocks keep theirs", () => {
render(<LandingPage company={company} frameBase="/f" page={page([
{ type: "HTML", html: "<header>Top</header>" }, ins, { type: "HTML", html: "<p>Rest</p>" }, { type: "RICH_TEXT", html: "<p>After</p>" },
])} />);
const rows = Array.from(document.querySelector("main > div")!.children);
expect(rows.map((r) => r.classList.contains("mt-10"))).toEqual([false, false, false, true]);
});
});
describe("utmTags", () => {
@@ -4,6 +4,7 @@ import type { RegistrationInfo } from "@/app/lib/services/publicRegistration";
import { SafeHtml } from "./SafeHtml";
import { LandingForm } from "./LandingForm";
import { HtmlFrame } from "./HtmlFrame";
import { EditContext, EditSection, HeroShade, HtmlSpot, ImageSpot, RichSpot, Text, stopNavigation, type PageEdit } from "./CmsEdit";
// Landing-page blocks, ported from babyboo's CmsBlocks minus the product blocks. HTML only goes through SafeHtml;
// images are this company's uploads; buttons render only for a safe link, checked again here. A Custom HTML block is
@@ -28,67 +29,141 @@ const BANDS: Record<Exclude<Look, "DEFAULT">, string> = {
};
const bandOf = (look: unknown) => (LOOKS.includes(look as Look) && look !== "DEFAULT" ? (look as Exclude<Look, "DEFAULT">) : null);
function ButtonLink({ block }: { block: CmsBlock }) {
if (!block.buttonLabel || !isSafeLink(block.buttonUrl)) return null;
function ButtonLink({ block, index, edit }: { block: CmsBlock; index: number; edit?: boolean }) {
// In edit mode a button with a label shows whatever its link, so its label can be typed in place.
if (!block.buttonLabel || (!edit && !isSafeLink(block.buttonUrl))) return null;
const external = /^https:/i.test(block.buttonUrl!);
const colours = bandOf(block.look) === "ACCENT" ? "bg-background text-foreground" : "bg-primary text-primary-foreground";
return (
<a href={block.buttonUrl} {...(external ? { target: "_blank", rel: "noopener noreferrer" } : {})}
className={`inline-flex h-11 items-center rounded-md px-5 text-sm font-medium hover:opacity-90 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none ${colours}`}>
{block.buttonLabel}
<Text as="span" index={index} path="buttonLabel" value={block.buttonLabel} max={40} code="PagesButtonLabel" />
</a>
);
}
function BlockImage({ id, className }: { id?: number | null; className: string }) {
// eslint-disable-next-line @next/next/no-img-element -- an uploaded image of unknown size
return id ? <img src={imageSrc(id)} alt="" className={className} /> : null;
}
function Block({ block, index, company, slug, preview }: { block: PublicBlock; index: number; company: string; slug: string; preview?: boolean }) {
function Block({ block, index, company, slug, preview, edit }: { block: PublicBlock; index: number; company: string; slug: string; preview?: boolean; edit?: boolean }) {
const image = block.imageId ? imageSrc(block.imageId) : undefined;
const button = <ButtonLink block={block} index={index} edit={edit} />;
switch (block.type) {
case "HERO":
case "HERO": {
const wide = !!block.fullWidth;
const points = block.cards?.length ? (
<ul className="space-y-2">
{block.cards.map((card, i) => (
<li key={i} className="flex items-baseline gap-3 before:size-2 before:shrink-0 before:rounded-full before:bg-primary">
<Text as="span" index={index} path={`cards.${i}.title`} value={card.title} max={80} code="PagesPointN" n={i + 1} />
</li>
))}
</ul>
) : null;
const words = (
<>
<Text as="h2" index={index} path="heading" value={block.heading} max={120} code="PagesHeading"
className={wide ? "font-serif text-4xl leading-tight font-semibold sm:text-5xl" : "text-3xl font-semibold sm:text-4xl"} />
<Text as="p" index={index} path="text" value={block.text} max={300} code="PagesText" className="max-w-2xl text-lg" />
{points}
<div>{button}</div>
</>
);
// add-hero-signup-form: with an event, the sign-up form sits in a card beside the text (below it on phones).
// add-hero-full-width: the card may open with its own heading and text.
const card = block.eventUuid ? (
<div className="space-y-4 rounded-lg border bg-card p-6 text-card-foreground shadow-card">
{block.formHeading || block.formText || edit ? (
<div className="space-y-1">
<Text as="h3" index={index} path="formHeading" value={block.formHeading} max={80} code="PagesFormHeading" className="font-serif text-2xl font-semibold" />
<Text as="p" index={index} path="formText" value={block.formText} max={200} code="PagesFormText" className="text-sm text-muted-foreground" />
</div>
) : null}
<LandingForm companyCode={company} slug={slug} index={index} info={block.closed ? undefined : block.form} preview={preview} />
</div>
) : null;
const back = bandOf(block.look) ? "" : "bg-muted";
if (wide) {
// Edge to edge; the shade is darkest behind the text and clears toward the far side. The text is centred in the
// hero's opening height, not beside a long form, so it stays in the first screen.
const grid = `mx-auto grid w-full max-w-6xl items-start gap-8 px-4 pt-16 pb-12 ${card ? "md:grid-cols-[minmax(0,1fr)_minmax(0,28rem)]" : ""}`;
return (
<section className={`relative overflow-hidden ${back}`}>
<ImageSpot index={index} src={image} className="absolute inset-0 h-full w-full object-cover" corner />
<HeroShade index={index} image={!!image} shaded="relative bg-gradient-to-r from-black/75 via-black/45 to-black/10 text-white" plain="">
<div className={grid}>
<div className="flex flex-col justify-center gap-4 md:min-h-[32rem]">{words}</div>
{card}
</div>
</HeroShade>
</section>
);
}
if (card) {
// Top padding leaves room for the editor's image button in the corner.
const grid = "grid items-start gap-6 px-6 pt-16 pb-6 md:grid-cols-[minmax(0,1fr)_minmax(0,26rem)] md:px-10 md:pb-10";
return (
<section className={`relative overflow-hidden rounded-lg ${back}`}>
<ImageSpot index={index} src={image} className="absolute inset-0 h-full w-full object-cover" corner />
<HeroShade index={index} image={!!image} shaded={`relative ${grid} bg-gradient-to-r from-black/80 via-black/60 to-black/40 text-white sm:min-h-96`} plain={grid}>
<div className="flex flex-col gap-3">{words}</div>
{card}
</HeroShade>
</section>
);
}
return (
<section className={`relative overflow-hidden rounded-lg ${bandOf(block.look) ? "" : "bg-muted"}`}>
<BlockImage id={block.imageId} className="absolute inset-0 h-full w-full object-cover" />
<div className={block.imageId ? "relative flex min-h-72 flex-col justify-end gap-3 bg-gradient-to-t from-black/80 via-black/50 to-transparent p-6 text-white sm:min-h-96" : "flex flex-col gap-3 p-6"}>
{block.heading ? <h2 className="text-3xl font-semibold sm:text-4xl">{block.heading}</h2> : null}
{block.text ? <p className="max-w-2xl text-lg">{block.text}</p> : null}
<div><ButtonLink block={block} /></div>
</div>
<section className={`relative overflow-hidden rounded-lg ${back}`}>
<ImageSpot index={index} src={image} className="absolute inset-0 h-full w-full object-cover" corner />
<HeroShade index={index} image={!!image}
shaded="relative flex min-h-72 flex-col justify-end gap-3 bg-gradient-to-t from-black/80 via-black/50 to-transparent p-6 text-white sm:min-h-96"
plain="flex flex-col gap-3 p-6">
{words}
</HeroShade>
</section>
);
}
case "RICH_TEXT":
return block.html ? <section><SafeHtml html={block.html} className={PROSE} /></section> : null;
return block.html || edit ? (
<section><RichSpot index={index} html={block.html} className={PROSE}>{block.html ? <SafeHtml html={block.html} className={PROSE} /> : null}</RichSpot></section>
) : null;
case "IMAGE_TEXT":
return (
<section className="grid items-center gap-6 md:grid-cols-2">
<BlockImage id={block.imageId} className={`w-full rounded-lg object-cover ${block.imagePosition === "RIGHT" ? "md:order-2" : ""}`} />
{image || edit ? (
<div className={block.imagePosition === "RIGHT" ? "md:order-2" : undefined}>
<ImageSpot index={index} src={image} className="w-full rounded-lg object-cover" />
</div>
) : null}
<div className="space-y-3">
{block.heading ? <h2 className="text-2xl font-semibold">{block.heading}</h2> : null}
{block.html ? <SafeHtml html={block.html} className={PROSE} /> : null}
<ButtonLink block={block} />
<Text as="h2" index={index} path="heading" value={block.heading} max={120} code="PagesHeading" className="text-2xl font-semibold" />
<RichSpot index={index} html={block.html} className={PROSE}>{block.html ? <SafeHtml html={block.html} className={PROSE} /> : null}</RichSpot>
{button}
</div>
</section>
);
case "FAQ":
return block.items?.length ? (
<section className="space-y-3">
{block.heading ? <h2 className="text-2xl font-semibold">{block.heading}</h2> : null}
<Text as="h2" index={index} path="heading" value={block.heading} max={120} code="PagesHeading" className="text-2xl font-semibold" />
<div className="divide-y rounded-lg border">
{block.items.map((item, i) => (
<details key={i} name={`faq-${index}`} className="group p-4">
<summary className="cursor-pointer font-medium">{item.question}</summary>
<p className="mt-2 whitespace-pre-line text-muted-foreground">{item.answer}</p>
</details>
))}
{block.items.map((item, i) => {
const question = <Text as="span" index={index} path={`items.${i}.question`} value={item.question} max={300} code="PagesQuestionN" n={i + 1} />;
const answer = <Text as="p" index={index} path={`items.${i}.answer`} value={item.answer} max={2000} code="PagesAnswerN" n={i + 1} multiline className="mt-2 whitespace-pre-line text-muted-foreground" />;
// In edit mode every answer shows: a <summary> would toggle on a click or a typed space.
return edit ? (
<div key={i} className="p-4"><p className="font-medium">{question}</p>{answer}</div>
) : (
<details key={i} name={`faq-${index}`} className="group p-4">
<summary className="cursor-pointer font-medium">{item.question}</summary>
{answer}
</details>
);
})}
</div>
</section>
) : null;
case "FORM":
return (
<section className="mx-auto w-full max-w-md space-y-4 rounded-lg border bg-card p-6 shadow-card">
{block.heading ? <h2 className="text-2xl font-semibold">{block.heading}</h2> : null}
<Text as="h2" index={index} path="heading" value={block.heading} max={120} code="PagesHeading" className="text-2xl font-semibold" />
<LandingForm companyCode={company} slug={slug} index={index} info={block.closed ? undefined : block.form} preview={preview} />
</section>
);
@@ -96,8 +171,8 @@ function Block({ block, index, company, slug, preview }: { block: PublicBlock; i
return (
<section className="space-y-6">
<div className="max-w-2xl space-y-2">
{block.heading ? <h2 className="text-2xl font-semibold sm:text-3xl">{block.heading}</h2> : null}
{block.text ? <p className="text-lg opacity-80">{block.text}</p> : null}
<Text as="h2" index={index} path="heading" value={block.heading} max={120} code="PagesHeading" className="text-2xl font-semibold sm:text-3xl" />
<Text as="p" index={index} path="text" value={block.text} max={300} code="PagesText" className="text-lg opacity-80" />
</div>
<ul className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
{(block.cards ?? []).map((card, i) => {
@@ -105,8 +180,8 @@ function Block({ block, index, company, slug, preview }: { block: PublicBlock; i
return (
<li key={i} className="space-y-2 rounded-lg border bg-card p-5 text-card-foreground shadow-card">
{Icon ? <Icon aria-hidden="true" className="size-7 text-primary" /> : null}
<h3 className="text-lg font-semibold">{card.title}</h3>
<p className="text-muted-foreground">{card.text}</p>
<Text as="h3" index={index} path={`cards.${i}.title`} value={card.title} max={80} code="PagesCardTitle" className="text-lg font-semibold" />
<Text as="p" index={index} path={`cards.${i}.text`} value={card.text} max={300} code="PagesCardText" className="text-muted-foreground" />
</li>
);
})}
@@ -116,14 +191,14 @@ function Block({ block, index, company, slug, preview }: { block: PublicBlock; i
case "STEPS":
return (
<section className="space-y-6">
{block.heading ? <h2 className="text-2xl font-semibold sm:text-3xl">{block.heading}</h2> : null}
<Text as="h2" index={index} path="heading" value={block.heading} max={120} code="PagesHeading" className="text-2xl font-semibold sm:text-3xl" />
<ol className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
{(block.cards ?? []).map((card, i) => (
<li key={i} className="flex gap-4">
<span aria-hidden="true" className="flex size-10 shrink-0 items-center justify-center rounded-full border-2 border-current text-lg font-semibold">{i + 1}</span>
<div className="space-y-1">
<h3 className="text-lg font-semibold">{card.title}</h3>
<p className="opacity-80">{card.text}</p>
<Text as="h3" index={index} path={`cards.${i}.title`} value={card.title} max={80} code="PagesCardTitle" className="text-lg font-semibold" />
<Text as="p" index={index} path={`cards.${i}.text`} value={card.text} max={300} code="PagesCardText" className="opacity-80" />
</div>
</li>
))}
@@ -134,16 +209,16 @@ function Block({ block, index, company, slug, preview }: { block: PublicBlock; i
return (
<section>
<ul className="flex flex-wrap items-center justify-center gap-x-8 gap-y-2 text-center font-medium">
{(block.cards ?? []).map((card, i) => <li key={i}>{card.title}</li>)}
{(block.cards ?? []).map((card, i) => <li key={i}><Text as="span" index={index} path={`cards.${i}.title`} value={card.title} max={80} code="PagesCardTitle" /></li>)}
</ul>
</section>
);
case "CTA":
return (
<section className="flex flex-col items-center gap-4 py-4 text-center">
<h2 className="text-2xl font-semibold sm:text-3xl">{block.heading}</h2>
{block.text ? <p className="max-w-2xl text-lg opacity-80">{block.text}</p> : null}
<ButtonLink block={block} />
<Text as="h2" index={index} path="heading" value={block.heading} max={120} code="PagesHeading" className="text-2xl font-semibold sm:text-3xl" />
<Text as="p" index={index} path="text" value={block.text} max={300} code="PagesText" className="max-w-2xl text-lg opacity-80" />
{button}
</section>
);
default:
@@ -153,14 +228,21 @@ function Block({ block, index, company, slug, preview }: { block: PublicBlock; i
const WIDTH = "mx-auto w-full max-w-5xl px-4";
/** Blocks that run the full window width: Custom HTML, and a full-width hero. Two of them in a row join with no gap. */
const bleeds = (block: PublicBlock) => block.type === "HTML" || (block.type === "HERO" && !!block.fullWidth);
/** A block in the page width; with a non-default look, inside a full-width band of that colour. */
function Section({ block, children }: { block: PublicBlock; children: ReactNode }) {
function Section({ block, index, children }: { block: PublicBlock; index: number; children: ReactNode }) {
const band = bandOf(block.look);
if (!band) return <div id={anchorId(block.anchor)} className={WIDTH}>{children}</div>;
// add-hero-full-width: a full-width hero sets its own width.
if (bleeds(block)) return <EditSection index={index}><div id={anchorId(block.anchor)}>{children}</div></EditSection>;
if (!band) return <EditSection index={index}><div id={anchorId(block.anchor)} className={WIDTH}>{children}</div></EditSection>;
return (
<div id={anchorId(block.anchor)} data-look={band} className={`py-12 ${BANDS[band]}`}>
<div className={WIDTH}>{children}</div>
</div>
<EditSection index={index}>
<div id={anchorId(block.anchor)} data-look={band} className={`py-12 ${BANDS[band]}`}>
<div className={WIDTH}>{children}</div>
</div>
</EditSection>
);
}
@@ -168,7 +250,7 @@ function Section({ block, children }: { block: PublicBlock; children: ReactNode
* A whole landing page: the company header (logo, accent), the title as the only h1, then the blocks. Custom HTML
* blocks run full width; with hideHeader the header goes and the title is for screen readers only.
*/
export function LandingPage({ company, page, banner, preview, frameBase }: {
export function LandingPage({ company, page, banner, preview, frameBase, edit }: {
company: Branding;
page: { slug: string; title: string; hideHeader?: boolean; blocks: PublicBlock[] };
banner?: ReactNode;
@@ -176,12 +258,14 @@ export function LandingPage({ company, page, banner, preview, frameBase }: {
preview?: boolean;
/** Where block frames load from; the public page's frame address by default. */
frameBase?: string;
/** The on-page editor's canvas (add-page-visual-editor): text edits in place and nothing navigates. */
edit?: PageEdit;
}) {
const frames = frameBase ?? `/p/${encodeURIComponent(company.code)}/${encodeURIComponent(page.slug)}/frame`;
const accent = company.accentColor && /^#[0-9A-Fa-f]{6}$/.test(company.accentColor) ? company.accentColor : null;
const style = accent ? ({ "--primary": accent, "--primary-foreground": contrastText(accent), "--ring": accent } as CSSProperties) : undefined;
return (
<div style={style} className="min-h-svh bg-background">
const body = (
<div style={style} className="min-h-svh bg-background" onClickCapture={edit ? stopNavigation : undefined}>
{banner}
{page.hideHeader ? null : <header className="border-b bg-card">
<div className="mx-auto flex max-w-5xl items-center gap-3 px-4 py-3">
@@ -195,12 +279,17 @@ export function LandingPage({ company, page, banner, preview, frameBase }: {
</header>}
<main className={page.hideHeader ? "pb-8" : "py-8"}>
<h1 className={page.hideHeader ? "sr-only" : `${WIDTH} mb-10 text-3xl font-semibold sm:text-4xl`}>{page.title}</h1>
<div className="space-y-10">
{page.blocks.map((block, i) => block.type === "HTML"
? <HtmlFrame key={i} id={anchorId(block.anchor)} src={`${frames}/${i}`} title={page.title} />
: <Section key={i} block={block}><Block block={block} index={i} company={company.code} slug={page.slug} preview={preview} /></Section>)}
<div>
{page.blocks.map((block, i) => (
<div key={i} className={i > 0 && !(bleeds(block) && bleeds(page.blocks[i - 1])) ? "mt-10" : undefined}>
{block.type === "HTML"
? <HtmlSpot index={i}><HtmlFrame id={anchorId(block.anchor)} src={`${frames}/${i}${edit ? `?v=${edit.frameVersion}` : ""}`} title={page.title} /></HtmlSpot>
: <Section block={block} index={i}><Block block={block} index={i} company={company.code} slug={page.slug} preview={preview} edit={!!edit} /></Section>}
</div>
))}
</div>
</main>
</div>
);
return edit ? <EditContext.Provider value={edit}>{body}</EditContext.Provider> : body;
}
@@ -0,0 +1,179 @@
"use client";
import { createContext, useContext, useLayoutEffect, useRef, type ElementType, type FormEvent, type KeyboardEvent, type MouseEvent, type ReactNode } from "react";
import dynamic from "next/dynamic";
import { ImagePlus } from "lucide-react";
import { BLOCK_LABELS, type CmsBlock } from "@/app/lib/cmsPages";
import { useT } from "@/app/lib/i18n/MessagesProvider";
// add-page-visual-editor: the landing page in edit mode, on the on-page editor's canvas. The public page and the
// preview never provide an edit context, so every part here renders exactly the public markup without one.
export interface PageEdit {
/** The selected block's index, or null. */
selected: number | null;
select(index: number): void;
/** A plain text field changed: `path` is "heading", "text", "buttonLabel", "cards.<i>.title|text" or "items.<i>.question|answer". */
text(index: number, path: string, value: string): void;
/** A rich text block's HTML changed. */
html(index: number, html: string): void;
/** An image spot was clicked: the editor opens its file picker. */
image(index: number): void;
/** A chosen image not yet uploaded, as a data URL. */
preview(index: number): string | undefined;
/** A Custom HTML block whose HTML has unsaved edits: its frame still shows the saved version. */
stale(index: number): boolean;
/** Bumped after each save, so Custom HTML frames reload the saved version. */
frameVersion: number;
/** The editor's own tools for a selected section (toolbar, add section). */
chrome(index: number): ReactNode;
}
export const EditContext = createContext<PageEdit | null>(null);
export const useEdit = () => useContext(EditContext);
/** The block with one plain text field set, by its path (see PageEdit.text). */
export function setField(block: CmsBlock, path: string, value: string): CmsBlock {
const [list, at, key] = path.split(".");
if (key === undefined) return { ...block, [list]: value };
const items = [...((block[list as "cards" | "items"] ?? []) as object[])];
items[Number(at)] = { ...items[Number(at)], [key]: value };
return { ...block, [list]: items };
}
/**
* A plain text field: the text as-is on the public page; in edit mode the same element, typed into in place. It is
* never re-rendered from its value while focused, so the caret stays where it is.
*/
export function Text({ as: Tag, index, path, value, max, code, n, className, multiline }: {
as: ElementType;
index: number;
path: string;
value: string | undefined;
max: number;
/** The field's label code, the editable's name; `n` fills its {number}. */
code: string;
n?: number;
className?: string;
multiline?: boolean;
}) {
const edit = useEdit();
if (!edit) return value ? <Tag className={className}>{value}</Tag> : null;
return <EditableText as={Tag} edit={edit} index={index} path={path} value={value ?? ""} max={max} code={code} n={n} className={className} multiline={multiline} />;
}
function EditableText({ as: Tag, edit, index, path, value, max, code, n, className, multiline }: {
as: ElementType; edit: PageEdit; index: number; path: string; value: string; max: number; code: string; n?: number; className?: string; multiline?: boolean;
}) {
const t = useT();
const ref = useRef<HTMLElement>(null);
useLayoutEffect(() => {
const el = ref.current;
if (el && el.ownerDocument.activeElement !== el && el.textContent !== value) el.textContent = value;
}, [value]);
const near = value.length > max * 0.8;
const name = t(code, n === undefined ? undefined : { number: n });
return (
<>
<Tag ref={ref} role="textbox" aria-label={name} aria-multiline={multiline || undefined} contentEditable="plaintext-only"
suppressContentEditableWarning data-placeholder={name}
className={`${className ?? ""} cursor-text rounded-sm outline-none hover:outline-dashed hover:outline-1 hover:outline-primary/50 focus:outline-2 focus:outline-primary empty:before:opacity-50 empty:before:content-[attr(data-placeholder)]`}
onInput={(e: FormEvent<HTMLElement>) => edit.text(index, path, e.currentTarget.textContent ?? "")}
onKeyDown={(e: KeyboardEvent) => { if (e.key === "Enter" && !multiline) e.preventDefault(); }} />
{near ? <span aria-live="polite" className={`text-xs tabular-nums ${value.length > max ? "text-destructive" : "opacity-60"}`}>{`${value.length}/${max}`}</span> : null}
</>
);
}
/**
* An image of a block: in edit mode a button that opens the editor's file picker, showing a chosen image at once.
* A background image (`corner`) stays as it is, with a small button in the corner instead.
*/
export function ImageSpot({ index, src, className, corner }: { index: number; src: string | undefined; className: string; corner?: boolean }) {
const t = useT();
const edit = useEdit();
const shown = edit?.preview(index) ?? src;
// eslint-disable-next-line @next/next/no-img-element -- an uploaded image of unknown size
const img = shown ? <img src={shown} alt="" className={className} /> : null;
if (!edit) return img;
const open = (e: MouseEvent) => { e.stopPropagation(); edit.select(index); edit.image(index); };
if (corner) {
return (
<>
{img}
<button type="button" aria-label={t("PagesImage")} onClick={open}
className="absolute top-3 left-3 z-10 flex size-10 cursor-pointer items-center justify-center rounded-full bg-background/90 text-foreground shadow hover:bg-background">
<ImagePlus aria-hidden="true" className="size-5" />
</button>
</>
);
}
return (
<button type="button" aria-label={t("PagesImage")} onClick={open}
className={`group/img relative block w-full cursor-pointer ${shown ? "" : "flex min-h-40 items-center justify-center rounded-lg border-2 border-dashed border-current/30"}`}>
{img ?? <ImagePlus aria-hidden="true" className="size-8 opacity-60" />}
<span className="absolute inset-0 rounded-lg ring-primary group-hover/img:ring-2" />
</button>
);
}
/** In edit mode, the whole page: clicks never follow a link or submit. */
export function stopNavigation(e: MouseEvent) {
if ((e.target as Element).closest("a[href], button[type=submit], form")) e.preventDefault();
}
/** A section's frame in edit mode: selected on click, outlined when hovered or selected, with the editor's tools. */
export function EditSection({ index, children }: { index: number; children: ReactNode }) {
const edit = useEdit();
if (!edit) return <>{children}</>;
const selected = edit.selected === index;
return (
<div data-index={index} data-selected={selected || undefined} onClick={() => edit.select(index)}
className={`group/section relative outline-offset-2 hover:outline-dashed hover:outline-1 hover:outline-primary/60 ${selected ? "outline-2 outline-primary hover:outline-solid hover:outline-2" : ""}`}>
{children}
{edit.chrome(index)}
</div>
);
}
/** A Custom HTML block in edit mode: its saved version, covered so a click selects it, marked while unsaved. */
export function HtmlSpot({ index, children }: { index: number; children: ReactNode }) {
const t = useT();
const edit = useEdit();
if (!edit) return <>{children}</>;
return (
<EditSection index={index}>
<div className="relative">
{children}
<button type="button" aria-label={t(BLOCK_LABELS.HTML)} className="absolute inset-0 cursor-pointer" onClick={() => edit.select(index)} />
{edit.stale(index) ? (
<span className="absolute top-2 left-2 rounded-md border border-warning/40 bg-background px-2 py-1 text-xs font-medium text-warning shadow">{t("PagesSaveToUpdate")}</span>
) : null}
</div>
</EditSection>
);
}
/** The hero's text area: shaded over an image, including one chosen in the editor and not saved yet. */
export function HeroShade({ index, image, shaded, plain, children }: { index: number; image: boolean; shaded: string; plain: string; children: ReactNode }) {
const edit = useEdit();
return <div className={image || edit?.preview(index) ? shaded : plain}>{children}</div>;
}
// Loaded only when the canvas shows rich text: visitors' pages never download the editor.
const RichTextEditor = dynamic(() => import("./RichTextEditor").then((m) => m.RichTextEditor), { ssr: false });
/** A block's rich text: the sanitised HTML on the public page (`children`); in edit mode, edited in place. */
export function RichSpot({ index, html, className, children }: { index: number; html: string | undefined; className: string; children: ReactNode }) {
const t = useT();
const edit = useEdit();
if (!edit) return <>{children}</>;
return (
<div className={`${className} relative ${html ? "" : "[&_.ProseMirror]:min-h-24"}`}>
{/* An empty editor is a thin line under the section's Add section button: it gets room, and a faded cue like
the plain fields' marks the spot to type. */}
{html ? null : <p aria-hidden="true" className="pointer-events-none absolute top-0 left-0 opacity-50">{t("PagesContent")}</p>}
<RichTextEditor bare label={t("PagesContent")} value={html ?? ""} onChange={(value) => edit.html(index, value)} />
</div>
);
}
@@ -1,25 +1,32 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { FRAME_SANDBOX, frameAnchor, nextFrameHeight, START_HEIGHT, type FrameHeight } from "@/app/lib/frameHtml";
import { FRAME_ASK_MESSAGE, FRAME_SANDBOX, frameAnchor, nextFrameHeight, START_HEIGHT, type FrameHeight } from "@/app/lib/frameHtml";
// add-hero-full-width: the frame may have reported before this page listened; ask on mount, and again when it loads.
const ask = (frame: HTMLIFrameElement | null) => frame?.contentWindow?.postMessage({ type: FRAME_ASK_MESSAGE }, "*");
/** A Custom HTML block: the sealed frame, sized by height reports and scrolled to by #name requests from that frame's own window only. */
export function HtmlFrame({ id, src, title }: { id?: string; src: string; title: string }) {
const ref = useRef<HTMLIFrameElement>(null);
const [size, setSize] = useState<FrameHeight>({ height: START_HEIGHT, steps: [] });
useEffect(() => {
// The frame's parent window: the page's, or the editor canvas's when rendered into it (add-page-visual-editor).
const host = ref.current?.ownerDocument.defaultView;
if (!host) return;
const onMessage = (e: MessageEvent) => {
const frame = ref.current;
if (!frame || e.source !== frame.contentWindow) return;
const anchor = frameAnchor(e.data);
if (!anchor) return setSize((s) => nextFrameHeight(s, e.data));
// add-page-anchor-links: the frame's own target first, else a named block of this page.
if (anchor.y !== null) return window.scrollTo({ top: frame.getBoundingClientRect().top + window.scrollY + anchor.y, behavior: "smooth" });
const block = document.getElementById(anchor.name);
if (anchor.y !== null) return host.scrollTo({ top: frame.getBoundingClientRect().top + host.scrollY + anchor.y, behavior: "smooth" });
const block = host.document.getElementById(anchor.name);
if (block?.closest("main")) block.scrollIntoView({ behavior: "smooth" });
};
window.addEventListener("message", onMessage);
return () => window.removeEventListener("message", onMessage);
host.addEventListener("message", onMessage);
ask(ref.current);
return () => host.removeEventListener("message", onMessage);
}, []);
return <iframe ref={ref} id={id} src={src} title={title} sandbox={FRAME_SANDBOX} loading="lazy" className="block w-full border-0" style={{ height: `${size.height}px` }} />;
return <iframe ref={ref} id={id} src={src} title={title} sandbox={FRAME_SANDBOX} loading="lazy" onLoad={(e) => ask(e.currentTarget)} className="block w-full border-0" style={{ height: `${size.height}px` }} />;
}
@@ -0,0 +1,51 @@
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import Link from "next/link";
import { describe, it, expect, vi, beforeEach } from "vitest";
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
import { memoryRouter } from "@/test/memoryRouter";
import { LeaveGuard } from "./LeaveGuard";
// add-page-visual-editor: unsaved edits are guarded against in-app links too, not only reloads.
beforeEach(() => memoryRouter.reset("/pages/5"));
const menu = (
<nav>
<Link href="/events">Events</Link>
<a href="/p/INS/hotel" target="_blank" rel="noopener noreferrer">View page</a>
<a href="#top">Top</a>
</nav>
);
describe("LeaveGuard", () => {
it("asks before an in-app link leaves unsaved edits: Cancel stays, Leave goes", async () => {
const user = userEvent.setup();
render(<>{menu}<LeaveGuard dirty /></>);
await user.click(screen.getByRole("link", { name: "Events" }));
expect(screen.getByRole("dialog", { name: "Leave without saving?" })).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Cancel" }));
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
expect(memoryRouter.push).not.toHaveBeenCalled();
await user.click(screen.getByRole("link", { name: "Events" }));
await user.click(screen.getByRole("button", { name: "Leave" }));
expect(memoryRouter.push).toHaveBeenCalledWith("/events");
});
it("lets links through when nothing is unsaved, and never stops a new tab or a link within the page", async () => {
const user = userEvent.setup();
const { rerender } = render(<>{menu}<LeaveGuard dirty={false} /></>);
await user.click(screen.getByRole("link", { name: "Events" }));
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
rerender(<>{menu}<LeaveGuard dirty /></>);
await user.click(screen.getByRole("link", { name: "View page" }));
await user.click(screen.getByRole("link", { name: "Top" }));
await user.keyboard("{Control>}");
await user.click(screen.getByRole("link", { name: "Events" }));
await user.keyboard("{/Control}");
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
});
});
@@ -0,0 +1,49 @@
"use client";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { ConfirmDialog } from "@/app/components/ui/confirm-dialog";
import { useT } from "@/app/lib/i18n/MessagesProvider";
/** The in-app address a plain left click on this event would go to, or null when the click stays or opens elsewhere. */
function leavingTo(e: MouseEvent): string | null {
if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return null;
const link = (e.target as Element | null)?.closest?.("a[href]") as HTMLAnchorElement | null;
if (!link || (link.target && link.target !== "_self") || link.hasAttribute("download")) return null;
const url = new URL(link.href, location.href);
if (url.origin !== location.origin) return null;
if (url.pathname === location.pathname && url.search === location.search) return null; // a #name on this page
return url.pathname + url.search + url.hash;
}
/**
* Asks before an in-app link leaves unsaved edits (add-page-visual-editor). The browser asks for reloads and closing
* (usePageDraft). ponytail: browser Back is not guarded; the App Router has no hook for it.
*/
export function LeaveGuard({ dirty }: { dirty: boolean }) {
const t = useT();
const router = useRouter();
const [to, setTo] = useState<string | null>(null);
useEffect(() => {
if (!dirty) return;
// Capture phase on the document: before the link's own handler, which then sees the click is taken.
const onClick = (e: MouseEvent) => {
const href = leavingTo(e);
if (!href) return;
e.preventDefault();
setTo(href);
};
document.addEventListener("click", onClick, true);
return () => document.removeEventListener("click", onClick, true);
}, [dirty]);
return to ? (
<ConfirmDialog
title={t("PagesLeaveTitle")}
message={t("PagesLeaveMessage")}
confirmLabel={t("PagesLeave")}
destructive
onConfirm={() => { setTo(null); router.push(to); }}
onCancel={() => setTo(null)}
/>
) : null;
}
@@ -0,0 +1,17 @@
import { render, waitFor, within } from "@testing-library/react";
import { describe, it, expect } from "vitest";
import { PageCanvas } from "./PageCanvas";
// add-page-visual-editor: the canvas is a device screen, Desktop 1280 px (scaled to fit) or Phone 390 px.
const frame = () => document.querySelector("iframe") as HTMLIFrameElement;
describe("PageCanvas", () => {
it("shows the page on a 1280 px desktop screen or a 390 px phone screen", async () => {
const { rerender } = render(<PageCanvas device="DESKTOP" title="Canvas"><p>Hello</p></PageCanvas>);
expect(frame()).toHaveStyle({ width: "1280px" });
await waitFor(() => expect(within(frame().contentDocument!.body).getByText("Hello")).toBeInTheDocument());
rerender(<PageCanvas device="PHONE" title="Canvas"><p>Hello</p></PageCanvas>);
expect(frame()).toHaveStyle({ width: "390px" });
expect(within(frame().contentDocument!.body).getByText("Hello")).toBeInTheDocument();
});
});
@@ -0,0 +1,36 @@
"use client";
import { useEffect, useRef, useState, type ReactNode } from "react";
import { CanvasFrame } from "./CanvasFrame";
export type Device = "DESKTOP" | "PHONE";
/**
* The on-page editor's canvas (add-page-visual-editor, design Decision 2): the page on a device screen. Desktop is a
* 1280 px screen scaled down to the space it has, so a laptop shows the desktop layout; Phone is 390 px at full size.
*/
export function PageCanvas({ device, title, children }: { device: Device; title: string; children: ReactNode }) {
const box = useRef<HTMLDivElement>(null);
const [space, setSpace] = useState({ width: 0, height: 0 });
useEffect(() => {
const el = box.current;
if (!el) return;
const measure = () => setSpace({ width: el.clientWidth, height: el.clientHeight });
const observer = new ResizeObserver(measure);
observer.observe(el);
measure();
return () => observer.disconnect();
}, []);
const width = device === "PHONE" ? 390 : 1280;
const scale = device === "PHONE" || !space.width ? 1 : Math.min(1, space.width / width);
const height = (space.height || 800) / scale;
return (
<div ref={box} className="h-full min-h-0 w-full overflow-hidden">
<div className={`mx-auto overflow-hidden ${device === "PHONE" ? "rounded-xl border shadow-card" : ""}`} style={{ width: width * scale, height: height * scale }}>
<div style={{ width, transform: scale === 1 ? undefined : `scale(${scale})`, transformOrigin: "top left" }}>
<CanvasFrame width={width} height={height} title={title}>{children}</CanvasFrame>
</div>
</div>
</div>
);
}
@@ -0,0 +1,40 @@
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import Link from "next/link";
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ getPage: vi.fn(), listAdminEvents: vi.fn(), useAdminAuth: vi.fn(), useCompanyScope: vi.fn() }));
vi.mock("@/app/lib/services/adminPages", () => ({ getPage: mocks.getPage }));
vi.mock("@/app/lib/services/adminEvents", () => ({ listAdminEvents: mocks.listAdminEvents }));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
vi.mock("@/app/lib/CompanyScope", () => ({ useCompanyScope: mocks.useCompanyScope }));
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
import { memoryRouter } from "@/test/memoryRouter";
import { PageEditor } from "./PageEditor";
// add-page-visual-editor: a menu link with unsaved edits asks first, in the form editor too.
beforeEach(() => {
vi.clearAllMocks();
memoryRouter.reset("/pages/5");
mocks.useAdminAuth.mockReturnValue({ isSuper: false, companyCode: "INS" });
mocks.useCompanyScope.mockReturnValue({ companyId: undefined, companies: [], codeOf: () => "INS" });
mocks.listAdminEvents.mockResolvedValue({ items: [], total: 0 });
mocks.getPage.mockResolvedValue({ id: 5, companyId: 2, slug: "hotel", title: "Hotel", metaDescription: null, status: "DRAFT", blocks: [] });
});
describe("PageEditor: leaving with unsaved edits", () => {
it("asks before a menu link only once something is changed", async () => {
const user = userEvent.setup();
render(<><Link href="/events">Events</Link><PageEditor pageId={5} /></>);
const title = await screen.findByLabelText("Title");
await user.click(screen.getByRole("link", { name: "Events" }));
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
await user.type(title, " day");
await user.click(screen.getByRole("link", { name: "Events" }));
expect(screen.getByRole("dialog", { name: "Leave without saving?" })).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Leave" }));
expect(memoryRouter.push).toHaveBeenCalledWith("/events");
});
});
@@ -56,7 +56,8 @@ describe("PageEditor", () => {
const user = userEvent.setup();
render(<PageEditor pageId={5} />);
const picker = await screen.findByLabelText("Event");
await waitFor(() => expect(screen.getByRole("option", { name: "Website enquiries" })).toBeInTheDocument());
// Scoped to the FORM block's picker: since add-hero-signup-form the hero offers the same events in its own picker.
await waitFor(() => expect(within(picker).getByRole("option", { name: "Website enquiries" })).toBeInTheDocument());
expect(screen.queryByRole("option", { name: "Old fair" })).not.toBeInTheDocument();
expect(picker).toHaveValue("3312726793093644288");
expect(screen.getByRole("link", { name: "View page" })).toHaveAttribute("href", "/p/INS/hotel");
@@ -106,6 +107,51 @@ describe("PageEditor", () => {
expect(memoryRouter.push).toHaveBeenCalledWith("/pages");
});
// add-hero-signup-form: the hero's own event picker, "No form" by default; its event is saved with the hero.
it("gives a hero a sign-up form for a chosen event, and No form takes it away", async () => {
const user = userEvent.setup();
render(<PageEditor pageId={5} />);
const picker = await screen.findByLabelText("Sign-up form");
expect(picker).toHaveValue("");
expect(within(picker).getByRole("option", { name: "No form" })).toBeInTheDocument();
await waitFor(() => expect(within(picker).getByRole("option", { name: "Website enquiries" })).toBeInTheDocument());
await user.selectOptions(picker, "3312726793093644288");
await user.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => expect(mocks.savePage).toHaveBeenCalledTimes(1));
expect(mocks.savePage.mock.calls[0][1].blocks[0]).toMatchObject({ type: "HERO", eventUuid: "3312726793093644288" });
await user.selectOptions(screen.getByLabelText("Sign-up form"), "");
await user.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => expect(mocks.savePage).toHaveBeenCalledTimes(2));
expect(mocks.savePage.mock.calls[1][1].blocks[0].eventUuid ?? null).toBeNull();
});
// add-hero-full-width: Full width, points, and the form card's heading and text (only while the hero has a form).
it("saves a full-width hero with points and a form heading; No form drops the heading and text", async () => {
const user = userEvent.setup();
render(<PageEditor pageId={5} />);
const picker = await screen.findByLabelText("Sign-up form");
expect(screen.queryByLabelText("Form heading")).not.toBeInTheDocument();
await user.click(screen.getByRole("switch", { name: "Full width" }));
await user.click(screen.getByRole("button", { name: "Add point" }));
await user.type(screen.getByRole("textbox", { name: "Point 1" }), "Local support team");
await waitFor(() => expect(within(picker).getByRole("option", { name: "Website enquiries" })).toBeInTheDocument());
await user.selectOptions(picker, "3312726793093644288");
await user.type(screen.getByLabelText("Form heading"), "Get a free consultation");
await user.type(screen.getByLabelText("Form text"), "It takes a minute.");
await user.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => expect(mocks.savePage).toHaveBeenCalledTimes(1));
expect(mocks.savePage.mock.calls[0][1].blocks[0]).toMatchObject({
type: "HERO", fullWidth: true, cards: [{ title: "Local support team" }],
formHeading: "Get a free consultation", formText: "It takes a minute.",
});
await user.selectOptions(screen.getByLabelText("Sign-up form"), "");
expect(screen.queryByLabelText("Form heading")).not.toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => expect(mocks.savePage).toHaveBeenCalledTimes(2));
const hero = mocks.savePage.mock.calls[1][1].blocks[0];
expect([hero.formHeading, hero.formText]).toEqual([undefined, undefined]);
});
it("a super admin must choose a company for a new page", async () => {
mocks.useAdminAuth.mockReturnValue({ isSuper: true, companyCode: null });
const user = userEvent.setup();
@@ -1,8 +1,7 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { useEffect, useRef, useState, useSyncExternalStore, type RefObject } from "react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { Button } from "@/app/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/app/components/ui/card";
import { ConfirmDialog } from "@/app/components/ui/confirm-dialog";
@@ -12,324 +11,203 @@ import { Switch } from "@/app/components/ui/switch";
import { Textarea } from "@/app/components/ui/textarea";
import { ErrorState } from "@/app/components/ui/states";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/app/components/ui/select";
import { ApiError } from "@/app/lib/clientApi";
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
import { useCompanyScope } from "@/app/lib/CompanyScope";
import { CopyAddress } from "./CopyAddress";
import { BLOCK_LABELS, BLOCK_TYPES, emptyBlock, emptyPage, pageAddress, pageBody, withTitle, type CmsBlock, type CmsPage, type CmsPageDraft, type PageStatus } from "@/app/lib/cmsPages";
import { deletePage, discardPage, getPage, publishPage, savePage, uploadPageImage } from "@/app/lib/services/adminPages";
import { listAdminEvents } from "@/app/lib/services/adminEvents";
import { BLOCK_LABELS, BLOCK_TYPES, pageAddress, type CmsBlock } from "@/app/lib/cmsPages";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import { BlockFields, type EventOption } from "./BlockFields";
import { BlockFields } from "./BlockFields";
import { usePageDraft } from "./usePageDraft";
import { LeaveGuard } from "./LeaveGuard";
import { VisualEditor } from "./visual/VisualEditor";
// The landing-page editor, ported from babyboo's PageEditor. Every block carries a stable key, so a chosen image
// follows its block through moves and removals. Block images upload on Save, just before the page is saved,
// each at most once even when a later step fails.
// The landing-page editor, ported from babyboo's PageEditor. State and actions live in usePageDraft, owned here so
// they survive a window resize that switches between the on-page editor (1024 px and up) and the form editor.
interface Row {
key: number;
block: CmsBlock;
}
export type Draft = ReturnType<typeof usePageDraft>;
/** Asks before the destructive actions; the dialogs are the editor's, whichever layout shows. */
export interface Ask { remove(): void; discard(): void }
function readDataUrl(file: File): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result as string);
reader.onerror = () => reject(reader.error);
reader.readAsDataURL(file);
});
}
const malaysiaToday = () => new Intl.DateTimeFormat("en-CA", { timeZone: "Asia/Kuala_Lumpur" }).format(new Date());
function FieldError({ message }: { message?: string }) {
export function FieldError({ message }: { message?: string }) {
return message ? <p role="alert" className="text-sm text-destructive">{message}</p> : null;
}
const WIDE = "(min-width: 1024px)";
const wideNow = () => window.matchMedia(WIDE).matches;
const onWideChange = (cb: () => void) => {
const query = window.matchMedia(WIDE);
query.addEventListener("change", cb);
return () => query.removeEventListener("change", cb);
};
/** pageId edits a page; fromId opens an unsaved copy of one (Duplicate); initialBlocks start a new page (templates). */
export function PageEditor({ pageId, fromId, initialBlocks }: { pageId?: number; fromId?: number; initialBlocks?: CmsBlock[] }) {
export function PageEditor(props: { pageId?: number; fromId?: number; initialBlocks?: CmsBlock[] }) {
const t = useT();
const router = useRouter();
const { isSuper, companyCode } = useAdminAuth();
const scope = useCompanyScope();
const justSaved = useSearchParams()?.get("saved") === "1";
const [draft, setDraft] = useState<CmsPageDraft>(() => ({ ...emptyPage(), companyId: scope.companyId }));
const [rows, setRows] = useState<Row[]>(() => (initialBlocks ?? []).map((block, i) => ({ key: -1 - i, block })));
const [pending, setPending] = useState<Record<number, { file: File; preview?: string }>>({});
// The page as last loaded or saved: what "View page" points at.
const [saved, setSaved] = useState<{ slug: string; status: PageStatus } | null>(null);
const [dirty, setDirty] = useState(false);
const loadId = pageId ?? fromId;
const [loading, setLoading] = useState(loadId != null);
const [loadError, setLoadError] = useState<string | null>(null);
const [errors, setErrors] = useState<Record<string, string>>({});
const [summary, setSummary] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(justSaved ? "PagesSaved" : null);
const [saving, setSaving] = useState(false);
const p = usePageDraft(props);
const wide = useSyncExternalStore(onWideChange, wideNow, () => false);
const [confirmDelete, setConfirmDelete] = useState(false);
const [confirmDiscard, setConfirmDiscard] = useState(false);
// A published page's edits are saved as a draft; visitors see the live version until Publish changes.
const [hasDraft, setHasDraft] = useState(false);
// Bumped when a save leaves a draft: Save sits below a long form, so the banner is scrolled into view.
const [revealDraft, setRevealDraft] = useState(0);
const ask: Ask = { remove: () => setConfirmDelete(true), discard: () => setConfirmDiscard(true) };
if (p.loadError) return <ErrorState message={t(p.loadError)} />;
if (p.loading) return null;
return (
<>
{wide ? <VisualEditor p={p} ask={ask} /> : <FormEditor p={p} ask={ask} />}
<LeaveGuard dirty={p.dirty} />
{confirmDiscard ? (
<ConfirmDialog
title={t("PagesDiscardTitle")}
message={t("PagesDiscardMessage", { title: p.draft.title })}
confirmLabel={t("PagesDiscardChanges")}
destructive
busy={p.saving}
onConfirm={() => void p.discardChanges().finally(() => setConfirmDiscard(false))}
onCancel={() => setConfirmDiscard(false)}
/>
) : null}
{confirmDelete ? (
<ConfirmDialog
title={t("PagesDeleteTitle")}
message={t("PagesDeleteMessage", { title: p.draft.title })}
confirmLabel={t("PagesDelete")}
destructive
busy={p.saving}
onConfirm={() => void p.remove().then((ok) => { if (!ok) setConfirmDelete(false); })}
onCancel={() => setConfirmDelete(false)}
/>
) : null}
</>
);
}
/** The page's own links: its address, Duplicate, Preview and, once published, View page. */
export function PageLinks({ p }: { p: Draft }) {
const t = useT();
const { draft, saved, code } = p;
return (
<>
{saved && code ? <span className="mr-auto"><CopyAddress address={pageAddress(code, saved.slug)} /></span> : null}
{draft.id != null ? (
<>
<Button variant="outline" asChild>
<Link href={`/pages/new?from=${draft.id}`}>{t("PagesDuplicate")}</Link>
</Button>
<Button variant="outline" asChild>
<Link href={`/pages/${draft.id}/preview`}>{t("PagesPreview")}</Link>
</Button>
</>
) : null}
{saved?.status === "PUBLISHED" && code ? (
<Button variant="outline" asChild>
<a href={pageAddress(code, saved.slug)} target="_blank" rel="noopener noreferrer">{t("PagesViewPage")}</a>
</Button>
) : null}
</>
);
}
/** The save outcome, and for a published page with unsaved-to-live edits, Publish changes and Discard changes. */
export function PageMessages({ p, ask, banner }: { p: Draft; ask: Ask; banner?: RefObject<HTMLDivElement | null> }) {
const t = useT();
return (
<>
{p.summary && <p role="alert" className="text-sm text-destructive">{p.summary}</p>}
{p.notice && <p role="status" className="text-sm text-positive">{t(p.notice)}</p>}
{p.hasDraft && p.draft.status === "PUBLISHED" ? (
<div ref={banner} className="flex scroll-mt-20 flex-wrap items-center gap-2 rounded-md border border-warning/30 bg-warning/10 px-3 py-2 text-sm">
<p className="mr-auto">{t("PagesDraftBanner")}</p>
<Button type="button" size="sm" variant="outline" disabled={p.saving} onClick={ask.discard}>{t("PagesDiscardChanges")}</Button>
<Button type="button" size="sm" disabled={p.saving} onClick={() => void p.publishChanges()}>{t("PagesPublishChanges")}</Button>
</div>
) : null}
</>
);
}
/** Company (a super admin's new page), title, slug and meta description. */
export function PageSettings({ p }: { p: Draft }) {
const t = useT();
const { draft, errors, saving, code } = p;
return (
<Card>
<CardHeader><CardTitle>{t("PagesPageCard")}</CardTitle></CardHeader>
<CardContent className="space-y-4">
{p.isSuper && p.isNew ? (
<div className="space-y-1.5">
<Label htmlFor="page-company">{t("Company")}</Label>
<Select value={draft.companyId ? String(draft.companyId) : ""} disabled={saving} onValueChange={(v) => p.changeCompany(Number(v))}>
<SelectTrigger id="page-company" aria-invalid={!!errors.companyId} className="w-full"><SelectValue placeholder={t("SelectCompany")} /></SelectTrigger>
<SelectContent>
{p.companies.map((c) => <SelectItem key={c.id} value={String(c.id)}>{c.code}</SelectItem>)}
</SelectContent>
</Select>
<FieldError message={errors.companyId} />
</div>
) : null}
<div className="space-y-1.5">
<Label htmlFor="page-title">{t("Title")}</Label>
<Input id="page-title" value={draft.title} disabled={saving} aria-invalid={!!errors.title} onChange={(e) => p.setTitle(e.target.value)} />
<FieldError message={errors.title} />
</div>
<div className="space-y-1.5">
<Label htmlFor="page-slug">{t("PagesSlug")}</Label>
<Input id="page-slug" value={draft.slug} disabled={saving} aria-invalid={!!errors.slug} onChange={(e) => p.patch({ slug: e.target.value, slugTouched: true })} />
<p className="text-xs text-muted-foreground">{t("PagesAddressHint", { address: pageAddress(code || "…", draft.slug || "…") })}</p>
<FieldError message={errors.slug} />
</div>
<div className="space-y-1.5">
<Label htmlFor="page-meta">{t("PagesMetaDescription")}</Label>
<Textarea id="page-meta" rows={3} value={draft.metaDescription} disabled={saving} aria-invalid={!!errors.metaDescription} onChange={(e) => p.patch({ metaDescription: e.target.value })} />
<p className="tabular text-xs text-muted-foreground">{`${draft.metaDescription.trim().length}/160`}</p>
<FieldError message={errors.metaDescription} />
</div>
</CardContent>
</Card>
);
}
/** Draft or published, and the hide-header switch. */
export function StatusSettings({ p }: { p: Draft }) {
const t = useT();
const { draft, errors, saving } = p;
return (
<Card>
<CardHeader><CardTitle>{t("Status")}</CardTitle></CardHeader>
<CardContent className="space-y-2">
{(["DRAFT", "PUBLISHED"] as const).map((s) => (
<label key={s} className="flex items-center gap-2 text-sm">
<input type="radio" name="page-status" value={s} checked={draft.status === s} disabled={saving} onChange={() => p.patch({ status: s })} />
{t(s === "PUBLISHED" ? "PagesPublished" : "PagesDraft")}
</label>
))}
<FieldError message={errors.status} />
<div className="flex items-center gap-2 pt-2 text-sm">
<Switch id="page-hide-header" checked={draft.hideHeader} disabled={saving} onCheckedChange={(on) => p.patch({ hideHeader: on })} />
<Label htmlFor="page-hide-header">{t("PagesHideHeader")}</Label>
</div>
</CardContent>
</Card>
);
}
/** The form editor: narrow windows. */
function FormEditor({ p, ask }: { p: Draft; ask: Ask }) {
const t = useT();
const { draft, rows, errors, saving } = p;
// Save sits below a long form, so the unpublished-changes banner is scrolled into view after a save that leaves one.
const draftBanner = useRef<HTMLDivElement>(null);
useEffect(() => {
if (revealDraft) draftBanner.current?.scrollIntoView?.({ behavior: "smooth", block: "nearest" });
}, [revealDraft]);
const [events, setEvents] = useState<EventOption[]>([]);
const nextKey = useRef(0);
const toRows = (blocks: CmsBlock[]) => blocks.map((block) => ({ key: ++nextKey.current, block }));
const isNew = draft.id == null;
/** Shows a loaded page: its draft when there is one, else the live content. */
function show(p: CmsPage) {
const c = p.draft ?? p;
setDraft({ id: p.id, companyId: p.companyId, slug: c.slug, slugTouched: true, title: c.title, metaDescription: c.metaDescription ?? "", status: p.status, hideHeader: !!c.hideHeader, blocks: [] });
setRows(toRows(c.blocks ?? []));
setPending({});
setSaved({ slug: p.slug, status: p.status });
setHasDraft(!!p.draft);
setDirty(false);
}
const code = (isSuper ? scope.codeOf(draft.companyId) : companyCode) || "";
useEffect(() => {
if (loadId == null) return;
let cancelled = false;
getPage(loadId)
.then((p) => {
if (cancelled) return;
show(p);
if (pageId == null) {
// Duplicate: the same company's content as a new, unsaved draft page.
setDraft((d) => ({ ...d, id: undefined, status: "DRAFT", title: `${d.title} (copy)`, slug: `${d.slug}-copy` }));
setSaved(null);
setHasDraft(false);
setDirty(true);
}
})
.catch((err: unknown) => { if (!cancelled) setLoadError(err instanceof ApiError && err.status === 404 ? "PagesNotFound" : "PagesLoadFailed"); })
.finally(() => { if (!cancelled) setLoading(false); });
return () => { cancelled = true; };
// eslint-disable-next-line react-hooks/exhaustive-deps -- show only sets state; load again only for another page.
}, [loadId]);
// The FORM picker: the page company's enabled events that have not ended (Malaysia dates).
const eventsCompany = isSuper ? draft.companyId : undefined;
useEffect(() => {
if (isSuper && !eventsCompany) return;
let live = true;
const today = malaysiaToday();
listAdminEvents({ enabled: "Y", page: 1, pageSize: 100, sortBy: "name", sortDir: "asc", companyId: eventsCompany })
.then((r) => { if (live) setEvents(r.items.filter((e) => !e.endDate || e.endDate >= today).map((e) => ({ uuid: e.uuid, name: e.name }))); })
.catch(() => {}); // the picker stays empty; a saved event still shows as unavailable
return () => { live = false; };
}, [isSuper, eventsCompany]);
// Unsaved edits: the browser asks before a reload or close. ponytail: in-app links are not guarded; add a router guard if staff lose work that way.
useEffect(() => {
if (!dirty) return;
const warn = (e: BeforeUnloadEvent) => e.preventDefault();
window.addEventListener("beforeunload", warn);
return () => window.removeEventListener("beforeunload", warn);
}, [dirty]);
const edit = <T,>(fn: (v: T) => void) => (v: T) => { setDirty(true); fn(v); };
const patch = edit((next: Partial<CmsPageDraft>) => setDraft((d) => ({ ...d, ...next })));
const updateBlock = (key: number, update: (block: CmsBlock) => CmsBlock) => {
setDirty(true);
setRows((rs) => rs.map((r) => (r.key === key ? { ...r, block: update(r.block) } : r)));
};
const moveBlock = (index: number, delta: -1 | 1) => {
setDirty(true);
setRows((rs) => {
const next = [...rs];
[next[index], next[index + delta]] = [next[index + delta], next[index]];
return next;
});
};
const removeBlock = (key: number) => {
setDirty(true);
setRows((rs) => rs.filter((r) => r.key !== key));
setPending(({ [key]: _dropped, ...rest }) => rest);
};
const chooseImage = (key: number, file: File) => {
setDirty(true);
setPending((p) => ({ ...p, [key]: { file } }));
readDataUrl(file)
.then((preview) => setPending((p) => (p[key]?.file === file ? { ...p, [key]: { file, preview } } : p)))
.catch(() => {});
};
function showError(err: unknown) {
const data = err instanceof ApiError ? (err.data as { code?: string; details?: { field?: string } } | undefined) : undefined;
const field = data?.details?.field;
const message = data?.code ? t(data.code) : t("PagesSaveFailed");
if (field) setErrors({ [field === "file" ? "blocks" : field]: message });
else setSummary(message);
}
async function save(): Promise<boolean> {
setSummary(null);
setNotice(null);
setErrors({});
if (isNew && isSuper && !draft.companyId) {
setErrors({ companyId: t("ChooseCompany") });
return false;
}
setSaving(true);
const next = rows.map((r) => ({ ...r }));
const left = { ...pending };
try {
for (const row of next) {
if (!left[row.key]) continue;
const data = (await readDataUrl(left[row.key].file)).split(",")[1];
row.block = { ...row.block, imageId: (await uploadPageImage(draft.companyId, data)).id };
delete left[row.key];
}
const page = await savePage(draft.id, pageBody({ ...draft, blocks: next.map((r) => r.block) }));
setDraft((d) => ({ ...d, id: page.id, companyId: page.companyId }));
setSaved({ slug: page.slug, status: page.status });
setHasDraft(!!page.draft);
if (page.draft) setRevealDraft((n) => n + 1);
setDirty(false);
setNotice("PagesSaved");
if (isNew) router.replace(`/pages/${page.id}?saved=1`);
return true;
} catch (err) {
showError(err);
return false;
} finally {
// Uploaded images stay on their blocks and leave the pending set, success or not.
setRows(next);
setPending(left);
setSaving(false);
}
}
/** Saves the current edits, then makes the draft live. */
async function publishChanges() {
if (draft.id == null || !(await save())) return;
setSaving(true);
try {
show(await publishPage(draft.id));
setNotice("PagesChangesPublished");
} catch (err) {
setNotice(null);
showError(err);
} finally {
setSaving(false);
}
}
async function discardChanges() {
if (draft.id == null) return;
setSaving(true);
setSummary(null);
setErrors({});
try {
show(await discardPage(draft.id));
setNotice("PagesChangesDiscarded");
} catch (err) {
showError(err);
} finally {
setConfirmDiscard(false);
setSaving(false);
}
}
async function remove() {
if (draft.id == null) return;
setSaving(true);
try {
await deletePage(draft.id);
setDirty(false);
router.push("/pages");
} catch (err) {
setConfirmDelete(false);
showError(err);
} finally {
setSaving(false);
}
}
if (loadError) return <ErrorState message={t(loadError)} />;
if (loading) return null;
const blockErrors = (index: number) => {
const prefix = `blocks[${index}].`;
return Object.fromEntries(Object.entries(errors).flatMap(([path, m]) => (path.startsWith(prefix) ? [[path.slice(prefix.length), m]] : [])));
};
if (p.revealDraft) draftBanner.current?.scrollIntoView?.({ behavior: "smooth", block: "nearest" });
}, [p.revealDraft]);
return (
<div className="space-y-4">
<div className="flex flex-wrap items-center justify-end gap-2">
{saved && code ? <span className="mr-auto"><CopyAddress address={pageAddress(code, saved.slug)} /></span> : null}
{draft.id != null ? (
<>
<Button variant="outline" asChild>
<Link href={`/pages/new?from=${draft.id}`}>{t("PagesDuplicate")}</Link>
</Button>
<Button variant="outline" asChild>
<Link href={`/pages/${draft.id}/preview`}>{t("PagesPreview")}</Link>
</Button>
</>
) : null}
{saved?.status === "PUBLISHED" && code ? (
<Button variant="outline" asChild>
<a href={pageAddress(code, saved.slug)} target="_blank" rel="noopener noreferrer">{t("PagesViewPage")}</a>
</Button>
) : null}
</div>
{summary && <p role="alert" className="text-sm text-destructive">{summary}</p>}
{notice && <p role="status" className="text-sm text-positive">{t(notice)}</p>}
{hasDraft && draft.status === "PUBLISHED" ? (
<div ref={draftBanner} className="flex scroll-mt-20 flex-wrap items-center gap-2 rounded-md border border-warning/30 bg-warning/10 px-3 py-2 text-sm">
<p className="mr-auto">{t("PagesDraftBanner")}</p>
<Button type="button" size="sm" variant="outline" disabled={saving} onClick={() => setConfirmDiscard(true)}>{t("PagesDiscardChanges")}</Button>
<Button type="button" size="sm" disabled={saving} onClick={() => void publishChanges()}>{t("PagesPublishChanges")}</Button>
</div>
) : null}
<div className="flex flex-wrap items-center justify-end gap-2"><PageLinks p={p} /></div>
<PageMessages p={p} ask={ask} banner={draftBanner} />
<div className="grid gap-4 lg:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">
<div className="space-y-4">
<Card>
<CardHeader><CardTitle>{t("PagesPageCard")}</CardTitle></CardHeader>
<CardContent className="space-y-4">
{isSuper && isNew ? (
<div className="space-y-1.5">
<Label htmlFor="page-company">{t("Company")}</Label>
<Select value={draft.companyId ? String(draft.companyId) : ""} disabled={saving}
onValueChange={(v) => { patch({ companyId: Number(v) }); setRows((rs) => rs.map((r) => (r.block.type === "FORM" ? { ...r, block: { ...r.block, eventUuid: null } } : r))); }}>
<SelectTrigger id="page-company" aria-invalid={!!errors.companyId} className="w-full"><SelectValue placeholder={t("SelectCompany")} /></SelectTrigger>
<SelectContent>
{scope.companies.map((c) => <SelectItem key={c.id} value={String(c.id)}>{c.code}</SelectItem>)}
</SelectContent>
</Select>
<FieldError message={errors.companyId} />
</div>
) : null}
<div className="space-y-1.5">
<Label htmlFor="page-title">{t("Title")}</Label>
<Input id="page-title" value={draft.title} disabled={saving} aria-invalid={!!errors.title}
onChange={(e) => { const v = e.target.value; setDirty(true); setDraft((d) => withTitle(d, v)); }} />
<FieldError message={errors.title} />
</div>
<div className="space-y-1.5">
<Label htmlFor="page-slug">{t("PagesSlug")}</Label>
<Input id="page-slug" value={draft.slug} disabled={saving} aria-invalid={!!errors.slug} onChange={(e) => patch({ slug: e.target.value, slugTouched: true })} />
<p className="text-xs text-muted-foreground">{t("PagesAddressHint", { address: pageAddress(code || "…", draft.slug || "…") })}</p>
<FieldError message={errors.slug} />
</div>
<div className="space-y-1.5">
<Label htmlFor="page-meta">{t("PagesMetaDescription")}</Label>
<Textarea id="page-meta" rows={3} value={draft.metaDescription} disabled={saving} aria-invalid={!!errors.metaDescription} onChange={(e) => patch({ metaDescription: e.target.value })} />
<p className="tabular text-xs text-muted-foreground">{`${draft.metaDescription.trim().length}/160`}</p>
<FieldError message={errors.metaDescription} />
</div>
</CardContent>
</Card>
<PageSettings p={p} />
{rows.map((row, index) => (
<BlockFields
key={row.key}
@@ -337,79 +215,38 @@ export function PageEditor({ pageId, fromId, initialBlocks }: { pageId?: number;
block={row.block}
index={index}
count={rows.length}
errors={blockErrors(index)}
errors={p.blockErrors(index)}
saving={saving}
events={events}
pendingImage={pending[row.key] && { name: pending[row.key].file.name, preview: pending[row.key].preview }}
onChange={(update) => updateBlock(row.key, update)}
onMove={(delta) => moveBlock(index, delta)}
onRemove={() => removeBlock(row.key)}
onChooseImage={(file) => chooseImage(row.key, file)}
events={p.events}
pendingImage={p.pending[row.key] && { name: p.pending[row.key].file.name, preview: p.pending[row.key].preview }}
onChange={(update) => p.updateBlock(row.key, update)}
onMove={(delta) => p.moveBlock(index, delta)}
onRemove={() => p.removeBlock(row.key)}
onChooseImage={(file) => p.chooseImage(row.key, file)}
/>
))}
<FieldError message={errors.blocks} />
<div className="flex flex-wrap gap-2">
{BLOCK_TYPES.map((type) => (
<Button key={type} type="button" variant="outline" size="sm" disabled={saving}
onClick={() => { setDirty(true); setRows((rs) => [...rs, { key: ++nextKey.current, block: emptyBlock(type) }]); }}>
<Button key={type} type="button" variant="outline" size="sm" disabled={saving} onClick={() => p.addBlock(type)}>
{t("PagesAddBlock", { type: t(BLOCK_LABELS[type]) })}
</Button>
))}
</div>
</div>
<div className="space-y-4">
<Card>
<CardHeader><CardTitle>{t("Status")}</CardTitle></CardHeader>
<CardContent className="space-y-2">
{(["DRAFT", "PUBLISHED"] as const).map((s) => (
<label key={s} className="flex items-center gap-2 text-sm">
<input type="radio" name="page-status" value={s} checked={draft.status === s} disabled={saving} onChange={() => patch({ status: s })} />
{t(s === "PUBLISHED" ? "PagesPublished" : "PagesDraft")}
</label>
))}
<FieldError message={errors.status} />
<div className="flex items-center gap-2 pt-2 text-sm">
<Switch id="page-hide-header" checked={draft.hideHeader} disabled={saving} onCheckedChange={(on) => patch({ hideHeader: on })} />
<Label htmlFor="page-hide-header">{t("PagesHideHeader")}</Label>
</div>
</CardContent>
</Card>
</div>
<div className="space-y-4"><StatusSettings p={p} /></div>
</div>
<div className="flex flex-wrap items-center justify-between gap-2">
{draft.id != null ? (
<Button type="button" variant="outline" className="text-destructive" disabled={saving} onClick={() => setConfirmDelete(true)}>
<Button type="button" variant="outline" className="text-destructive" disabled={saving} onClick={ask.remove}>
{t("PagesDelete")}
</Button>
) : <span />}
<Button type="button" disabled={saving} onClick={() => void save()}>{t("Save")}</Button>
<Button type="button" disabled={saving} onClick={() => void p.save()}>{t("Save")}</Button>
</div>
{confirmDiscard ? (
<ConfirmDialog
title={t("PagesDiscardTitle")}
message={t("PagesDiscardMessage", { title: draft.title })}
confirmLabel={t("PagesDiscardChanges")}
destructive
busy={saving}
onConfirm={() => void discardChanges()}
onCancel={() => setConfirmDiscard(false)}
/>
) : null}
{confirmDelete ? (
<ConfirmDialog
title={t("PagesDeleteTitle")}
message={t("PagesDeleteMessage", { title: draft.title })}
confirmLabel={t("PagesDelete")}
destructive
busy={saving}
onConfirm={() => void remove()}
onCancel={() => setConfirmDelete(false)}
/>
) : null}
</div>
);
}
@@ -0,0 +1,25 @@
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect, vi } from "vitest";
import { RichTextEditor } from "./RichTextEditor";
// add-page-visual-editor: links follow the page link rule, and a refused one says why instead of vanishing.
describe("RichTextEditor", () => {
it("refuses an unsafe link with a message, and adds nothing", async () => {
const user = userEvent.setup();
const onChange = vi.fn();
vi.spyOn(window, "prompt").mockReturnValue("javascript:alert(1)");
render(<RichTextEditor label="Content" value="<p>Hello</p>" onChange={onChange} />);
await screen.findByRole("textbox", { name: "Content" });
await user.click(screen.getByRole("button", { name: "Link" }));
expect(screen.getByRole("alert")).toHaveTextContent("That link is not allowed");
expect(onChange).not.toHaveBeenCalled();
});
it("in bare mode drops the box and keeps the toolbar for when the text is being edited", async () => {
render(<RichTextEditor bare label="Content" value="<p>Hello</p>" onChange={() => {}} />);
const box = await screen.findByRole("textbox", { name: "Content" });
expect(box.closest(".border")).toBeNull();
expect(screen.getByRole("toolbar", { name: "Formatting" })).toBeInTheDocument();
});
});
@@ -1,6 +1,6 @@
"use client";
import { useEffect, useRef, type ReactNode } from "react";
import { useEffect, useRef, useState, type ReactNode } from "react";
import { EditorContent, useEditor, useEditorState, type Editor } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import TextAlign from "@tiptap/extension-text-align";
@@ -15,15 +15,18 @@ import { isSafeLink } from "@/app/lib/cmsPages";
const htmlOf = (editor: Editor) => (editor.isEmpty ? "" : editor.getHTML());
export function RichTextEditor({ id, label, value, onChange, disabled, invalid }: {
export function RichTextEditor({ id, label, value, onChange, disabled, invalid, bare }: {
id?: string;
label?: string;
value: string;
onChange: (html: string) => void;
disabled?: boolean;
invalid?: boolean;
/** On the page canvas (add-page-visual-editor): the text in the page's own style, the toolbar floating above it while edited. */
bare?: boolean;
}) {
const t = useT();
const [refused, setRefused] = useState(false);
const emitted = useRef(value);
const editor = useEditor({
immediatelyRender: false,
@@ -37,7 +40,7 @@ export function RichTextEditor({ id, label, value, onChange, disabled, invalid }
}),
TextAlign.configure({ types: ["heading", "paragraph"], alignments: ["left", "center", "right"] }),
],
editorProps: { attributes: { ...(id ? { id } : {}), ...(label ? { "aria-label": label } : {}), ...(invalid ? { "aria-invalid": "true" } : {}), class: "min-h-[140px] px-3 py-2 text-sm outline-none" } },
editorProps: { attributes: { ...(id ? { id } : {}), ...(label ? { "aria-label": label } : {}), ...(invalid ? { "aria-invalid": "true" } : {}), class: bare ? "min-h-[1.5em] outline-none" : "min-h-[140px] px-3 py-2 text-sm outline-none" } },
onUpdate: ({ editor }) => {
const html = htmlOf(editor);
emitted.current = html;
@@ -76,13 +79,17 @@ export function RichTextEditor({ id, label, value, onChange, disabled, invalid }
function addLink() {
const url = window.prompt(t("PagesLinkPrompt"));
setRefused(!!url && !isSafeLink(url));
if (!url || !isSafeLink(url)) return;
run((e) => e.chain().focus().extendMarkRange("link").setLink({ href: url }).run());
}
const toolbar = bare
? "absolute bottom-full left-0 z-20 mb-2 hidden flex-wrap items-center gap-1 rounded-md border bg-popover p-1 text-popover-foreground shadow-md group-focus-within/rt:flex"
: "flex flex-wrap items-center gap-1";
return (
<div className="space-y-2">
<div className="flex flex-wrap items-center gap-1" role="toolbar" aria-label={t("PagesToolbar")}>
<div className={bare ? "group/rt relative rounded-sm hover:outline-dashed hover:outline-1 hover:outline-primary/50 focus-within:outline-2 focus-within:outline-primary" : "space-y-2"}>
<div className={toolbar} role="toolbar" aria-label={t("PagesToolbar")}>
<select aria-label={t("PagesTextStyle")} title={t("PagesTextStyle")} disabled={off} value={state?.level ?? "0"}
className="h-9 rounded-md border border-input bg-transparent px-2 text-sm"
onChange={(ev) => {
@@ -106,10 +113,11 @@ export function RichTextEditor({ id, label, value, onChange, disabled, invalid }
{btn(t("PagesDivider"), <Minus />, () => run((e) => e.chain().focus().setHorizontalRule().run()))}
{btn(t("PagesLink"), <LinkIcon />, addLink, state?.active.link)}
{btn(t("PagesClearFormatting"), <Eraser />, () => run((e) => e.chain().focus().unsetAllMarks().clearNodes().run()))}
{refused ? <p role="alert" className="basis-full px-1 text-sm text-destructive">{t("PagesLinkRefused")}</p> : null}
</div>
<div className="rounded-md border border-input [&_.ProseMirror_a]:underline [&_.ProseMirror_blockquote]:border-l-2 [&_.ProseMirror_blockquote]:pl-3 [&_.ProseMirror_h2]:text-xl [&_.ProseMirror_h2]:font-semibold [&_.ProseMirror_h3]:text-lg [&_.ProseMirror_h3]:font-semibold [&_.ProseMirror_ol]:list-decimal [&_.ProseMirror_ol]:pl-5 [&_.ProseMirror_ul]:list-disc [&_.ProseMirror_ul]:pl-5">
{bare ? <EditorContent editor={editor} /> : <div className="rounded-md border border-input [&_.ProseMirror_a]:underline [&_.ProseMirror_blockquote]:border-l-2 [&_.ProseMirror_blockquote]:pl-3 [&_.ProseMirror_h2]:text-xl [&_.ProseMirror_h2]:font-semibold [&_.ProseMirror_h3]:text-lg [&_.ProseMirror_h3]:font-semibold [&_.ProseMirror_ol]:list-decimal [&_.ProseMirror_ol]:pl-5 [&_.ProseMirror_ul]:list-disc [&_.ProseMirror_ul]:pl-5">
<EditorContent editor={editor} />
</div>
</div>}
</div>
);
}
@@ -0,0 +1,167 @@
import { act, renderHook, waitFor } from "@testing-library/react";
import { describe, it, expect, vi, beforeEach } from "vitest";
import { ApiError } from "@/app/lib/clientApi";
const mocks = vi.hoisted(() => ({ getPage: vi.fn(), savePage: vi.fn(), listAdminEvents: vi.fn(), useAdminAuth: vi.fn(), useCompanyScope: vi.fn() }));
vi.mock("@/app/lib/services/adminPages", () => ({ getPage: mocks.getPage, savePage: mocks.savePage }));
vi.mock("@/app/lib/services/adminEvents", () => ({ listAdminEvents: mocks.listAdminEvents }));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
vi.mock("@/app/lib/CompanyScope", () => ({ useCompanyScope: mocks.useCompanyScope }));
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
import { memoryRouter } from "@/test/memoryRouter";
import { moveItem, usePageDraft } from "./usePageDraft";
// add-page-visual-editor: the on-page editor's selection, section actions, undo and refusal mapping.
const stored = {
id: 5, companyId: 2, slug: "hotel", title: "Hotel", metaDescription: null, status: "DRAFT" as const,
company: { code: "INS", name: "INS Sdn Bhd", logoImageId: 4, accentColor: null },
blocks: [
{ type: "HERO" as const, heading: "Hi" },
{ type: "FAQ" as const, items: [{ question: "Q", answer: "A" }] },
{ type: "HTML" as const, html: "<p>x</p>" },
],
};
beforeEach(() => {
vi.clearAllMocks();
memoryRouter.reset("/pages/5");
mocks.useAdminAuth.mockReturnValue({ isSuper: false, companyCode: "INS" });
mocks.useCompanyScope.mockReturnValue({ companyId: undefined, companies: [], codeOf: () => "INS" });
mocks.listAdminEvents.mockResolvedValue({ items: [], total: 0 });
mocks.getPage.mockResolvedValue(stored);
mocks.savePage.mockImplementation(async (id: number, body: object) => ({ ...stored, ...body, id }));
});
async function loaded() {
const hook = renderHook(() => usePageDraft({ pageId: 5 }));
await waitFor(() => expect(hook.result.current.loading).toBe(false));
return hook;
}
const types = (r: { current: ReturnType<typeof usePageDraft> }) => r.current.rows.map((row) => row.block.type);
describe("moveItem", () => {
it("moves one item to a new place, keeping the others in order", () => {
expect(moveItem(["a", "b", "c", "d"], 0, 2)).toEqual(["b", "c", "a", "d"]);
expect(moveItem(["a", "b", "c", "d"], 3, 1)).toEqual(["a", "d", "b", "c"]);
expect(moveItem(["a", "b"], 1, 1)).toEqual(["a", "b"]);
});
});
describe("usePageDraft for the on-page editor", () => {
it("a company switch clears the event of every FORM block and of a hero's sign-up form", async () => {
mocks.getPage.mockResolvedValueOnce({ ...stored, blocks: [
{ type: "HERO" as const, heading: "Hi", eventUuid: "77" }, { type: "FORM" as const, eventUuid: "77" }, { type: "HERO" as const, heading: "Plain" },
] });
const { result } = await loaded();
act(() => result.current.changeCompany(3));
expect(result.current.rows.map((r) => r.block.eventUuid ?? null)).toEqual([null, null, null]);
});
// add-hero-full-width: the form card's heading and text go with the form, or the server refuses the save.
it("a company switch also drops a hero's form heading and text", async () => {
mocks.getPage.mockResolvedValueOnce({ ...stored, blocks: [
{ type: "HERO" as const, heading: "Hi", eventUuid: "77", formHeading: "Get a free consultation", formText: "Quick." },
] });
const { result } = await loaded();
act(() => result.current.changeCompany(3));
expect(result.current.rows[0].block).toEqual({ type: "HERO", heading: "Hi", eventUuid: null });
});
it("keeps the company's branding from the loaded page", async () => {
const { result } = await loaded();
expect(result.current.branding).toEqual(stored.company);
});
it("duplicates a section below itself and selects the copy", async () => {
const { result } = await loaded();
act(() => result.current.duplicateBlock(1));
expect(types(result)).toEqual(["HERO", "FAQ", "FAQ", "HTML"]);
expect(result.current.rows[2].block).toEqual(result.current.rows[1].block);
expect(result.current.rows[2].key).not.toBe(result.current.rows[1].key);
expect(result.current.selected).toBe(2);
});
it("adds a section between two and selects it", async () => {
const { result } = await loaded();
act(() => result.current.insertBlock(1, "STEPS"));
expect(types(result)).toEqual(["HERO", "STEPS", "FAQ", "HTML"]);
expect(result.current.selected).toBe(1);
});
it("brings an added, duplicated or moved section into view", async () => {
const { result } = await loaded();
act(() => result.current.addBlock("CTA"));
expect(result.current.revealed).toMatchObject({ index: 3 });
act(() => result.current.duplicateBlock(0));
expect(result.current.revealed).toMatchObject({ index: 1 });
act(() => result.current.moveBlock(0, 1));
expect(result.current.revealed).toMatchObject({ index: 1 });
act(() => result.current.moveBlockTo(4, 0));
expect(result.current.revealed).toMatchObject({ index: 0 });
});
it("drags a section to a new place, and the selection follows it", async () => {
const { result } = await loaded();
act(() => result.current.select(0));
act(() => result.current.moveBlockTo(0, 2));
expect(types(result)).toEqual(["FAQ", "HTML", "HERO"]);
expect(result.current.selected).toBe(2);
});
it("undoes typing in one field as one step, redoes it, and keeps history across a save", async () => {
const { result } = await loaded();
const key = result.current.rows[0].key;
act(() => result.current.text(key, "heading", "Ho"));
act(() => result.current.text(key, "heading", "Hot"));
act(() => result.current.text(key, "heading", "Hotel week"));
await act(async () => { await result.current.save(); });
expect(result.current.canUndo).toBe(true);
act(() => result.current.undo());
expect(result.current.rows[0].block.heading).toBe("Hi");
expect(result.current.canUndo).toBe(false);
act(() => result.current.redo());
expect(result.current.rows[0].block.heading).toBe("Hotel week");
});
it("brings a deleted section back in its place with its content", async () => {
const { result } = await loaded();
act(() => result.current.removeBlock(result.current.rows[1].key));
expect(types(result)).toEqual(["HERO", "HTML"]);
act(() => result.current.undo());
expect(types(result)).toEqual(["HERO", "FAQ", "HTML"]);
expect(result.current.rows[1].block.items).toEqual([{ question: "Q", answer: "A" }]);
});
it("keeps at most 50 steps", async () => {
const { result } = await loaded();
for (let i = 0; i < 55; i++) act(() => result.current.insertBlock(0, "CTA"));
let undone = 0;
while (result.current.canUndo) { act(() => result.current.undo()); undone++; }
expect(undone).toBe(50);
});
it("marks a Custom HTML block stale once its HTML or place differs from the saved page, until the next save", async () => {
const { result } = await loaded();
expect(result.current.stale(2)).toBe(false);
act(() => result.current.updateBlock(result.current.rows[2].key, (b) => ({ ...b, html: "<p>y</p>" })));
expect(result.current.stale(2)).toBe(true);
const version = result.current.frameVersion;
await act(async () => { await result.current.save(); });
expect(result.current.stale(2)).toBe(false);
expect(result.current.frameVersion).toBe(version + 1);
act(() => result.current.moveBlockTo(2, 0));
expect(result.current.stale(0)).toBe(true);
});
it("selects the block a refusal names, and clears the selection for a page field", async () => {
const { result } = await loaded();
mocks.savePage.mockRejectedValueOnce(new ApiError("x", 422, { code: "PagesEventRequired", details: { field: "blocks[1].eventUuid" } }));
await act(async () => { await result.current.save(); });
expect(result.current.selected).toBe(1);
expect(result.current.revealed).toEqual({ index: 1, n: 1 });
mocks.savePage.mockRejectedValueOnce(new ApiError("x", 422, { code: "PagesSlugTaken", details: { field: "slug" } }));
await act(async () => { await result.current.save(); });
expect(result.current.selected).toBeNull();
});
});
@@ -0,0 +1,390 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { ApiError } from "@/app/lib/clientApi";
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
import { useCompanyScope } from "@/app/lib/CompanyScope";
import { emptyBlock, emptyPage, pageBody, withTitle, type BlockType, type CmsBlock, type CmsPage, type CmsPageDraft, type PageStatus } from "@/app/lib/cmsPages";
import { setField } from "./CmsEdit";
import { deletePage, discardPage, getPage, publishPage, savePage, uploadPageImage } from "@/app/lib/services/adminPages";
import { listAdminEvents } from "@/app/lib/services/adminEvents";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import type { EventOption } from "./BlockFields";
// The landing-page editor's state and actions, shared by the form editor and the on-page editor
// (add-page-visual-editor). Every block carries a stable key, so a chosen image follows its block through moves and
// removals. Block images upload on Save, just before the page is saved, each at most once even when a later step fails.
export interface Row {
key: number;
block: CmsBlock;
}
export function readDataUrl(file: File): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result as string);
reader.onerror = () => reject(reader.error);
reader.readAsDataURL(file);
});
}
/** The list with one item moved from one place to another. */
export function moveItem<T>(list: T[], from: number, to: number): T[] {
const next = [...list];
const [item] = next.splice(from, 1);
next.splice(to, 0, item);
return next;
}
type Pending = Record<number, { file: File; preview?: string }>;
/** One undo step: the page as it was. */
interface Snapshot { draft: CmsPageDraft; rows: Row[]; pending: Pending }
const HISTORY = 50;
const malaysiaToday = () => new Intl.DateTimeFormat("en-CA", { timeZone: "Asia/Kuala_Lumpur" }).format(new Date());
/** pageId edits a page; fromId opens an unsaved copy of one (Duplicate); initialBlocks start a new page (templates). */
export function usePageDraft({ pageId, fromId, initialBlocks }: { pageId?: number; fromId?: number; initialBlocks?: CmsBlock[] }) {
const t = useT();
const router = useRouter();
const { isSuper, companyCode } = useAdminAuth();
const scope = useCompanyScope();
const justSaved = useSearchParams()?.get("saved") === "1";
const [draft, setDraft] = useState<CmsPageDraft>(() => ({ ...emptyPage(), companyId: scope.companyId }));
const [rows, setRows] = useState<Row[]>(() => (initialBlocks ?? []).map((block, i) => ({ key: -1 - i, block })));
const [pending, setPending] = useState<Pending>({});
// The page as last loaded or saved: what "View page" points at.
const [saved, setSaved] = useState<{ slug: string; status: PageStatus } | null>(null);
const [dirty, setDirty] = useState(false);
const loadId = pageId ?? fromId;
const [loading, setLoading] = useState(loadId != null);
const [loadError, setLoadError] = useState<string | null>(null);
const [errors, setErrors] = useState<Record<string, string>>({});
const [summary, setSummary] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(justSaved ? "PagesSaved" : null);
const [saving, setSaving] = useState(false);
// A published page's edits are saved as a draft; visitors see the live version until Publish changes.
const [hasDraft, setHasDraft] = useState(false);
// Bumped when a save leaves a draft, so the editor can bring its banner into view.
const [revealDraft, setRevealDraft] = useState(0);
const [events, setEvents] = useState<EventOption[]>([]);
const [branding, setBranding] = useState<CmsPage["company"]>(undefined);
// The on-page editor (add-page-visual-editor): the selected block, and a block to bring into view (a refusal).
const [selected, setSelected] = useState<number | null>(null);
const [revealed, setRevealed] = useState<{ index: number; n: number } | null>(null);
// Custom HTML blocks as last loaded or saved, by block key: the canvas shows that version until the next save.
const [savedHtml, setSavedHtml] = useState<Record<number, { index: number; html?: string }>>({});
const [frameVersion, setFrameVersion] = useState(0);
const [past, setPast] = useState<Snapshot[]>([]);
const [future, setFuture] = useState<Snapshot[]>([]);
// The field being typed into: typing on in it stays one undo step.
const typing = useRef<string | null>(null);
const nextKey = useRef(0);
const toRows = (blocks: CmsBlock[]) => blocks.map((block) => ({ key: ++nextKey.current, block }));
const isNew = draft.id == null;
const remember = (rs: Row[]) => {
setSavedHtml(Object.fromEntries(rs.flatMap((r, index) => (r.block.type === "HTML" ? [[r.key, { index, html: r.block.html }]] : []))));
setFrameVersion((v) => v + 1);
};
/** Shows a loaded page: its draft when there is one, else the live content. */
function show(p: CmsPage) {
const c = p.draft ?? p;
setDraft({ id: p.id, companyId: p.companyId, slug: c.slug, slugTouched: true, title: c.title, metaDescription: c.metaDescription ?? "", status: p.status, hideHeader: !!c.hideHeader, blocks: [] });
if (p.company) setBranding(p.company);
const loadedRows = toRows(c.blocks ?? []);
setRows(loadedRows);
remember(loadedRows);
setPending({});
setSaved({ slug: p.slug, status: p.status });
setHasDraft(!!p.draft);
setDirty(false);
}
const code = (isSuper ? scope.codeOf(draft.companyId) : companyCode) || "";
useEffect(() => {
if (loadId == null) return;
let cancelled = false;
getPage(loadId)
.then((p) => {
if (cancelled) return;
show(p);
if (pageId == null) {
// Duplicate: the same company's content as a new, unsaved draft page.
setDraft((d) => ({ ...d, id: undefined, status: "DRAFT", title: `${d.title} (copy)`, slug: `${d.slug}-copy` }));
setSaved(null);
setHasDraft(false);
setDirty(true);
}
})
.catch((err: unknown) => { if (!cancelled) setLoadError(err instanceof ApiError && err.status === 404 ? "PagesNotFound" : "PagesLoadFailed"); })
.finally(() => { if (!cancelled) setLoading(false); });
return () => { cancelled = true; };
// eslint-disable-next-line react-hooks/exhaustive-deps -- show only sets state; load again only for another page.
}, [loadId]);
// The FORM picker: the page company's enabled events that have not ended (Malaysia dates).
const eventsCompany = isSuper ? draft.companyId : undefined;
useEffect(() => {
if (isSuper && !eventsCompany) return;
let live = true;
const today = malaysiaToday();
listAdminEvents({ enabled: "Y", page: 1, pageSize: 100, sortBy: "name", sortDir: "asc", companyId: eventsCompany })
.then((r) => { if (live) setEvents(r.items.filter((e) => !e.endDate || e.endDate >= today).map((e) => ({ uuid: e.uuid, name: e.name }))); })
.catch(() => {}); // the picker stays empty; a saved event still shows as unavailable
return () => { live = false; };
}, [isSuper, eventsCompany]);
// Unsaved edits: the browser asks before a reload or close.
useEffect(() => {
if (!dirty) return;
const warn = (e: BeforeUnloadEvent) => e.preventDefault();
window.addEventListener("beforeunload", warn);
return () => window.removeEventListener("beforeunload", warn);
}, [dirty]);
/**
* Starts a change: one undo step per action, and per field while it is typed into (`field`), until another field
* or action. Marks the page unsaved.
*/
const step = (field: string | null) => {
if (field === null || typing.current !== field) {
setPast((p) => [...p, { draft, rows, pending }].slice(-HISTORY));
setFuture([]);
}
typing.current = field;
setDirty(true);
};
/** Typing in a field ended (it lost focus): the next change is a new step. */
const endTyping = () => { typing.current = null; };
/** Puts back a snapshot, keeping the page's identity (an undo past the first save must not create a second page). */
const restore = (s: Snapshot) => {
setDraft({ ...s.draft, id: draft.id, companyId: draft.id != null ? draft.companyId : s.draft.companyId });
setRows(s.rows);
setPending(s.pending);
typing.current = null;
setDirty(true);
};
const undo = () => {
const prev = past.at(-1);
if (!prev) return;
setPast(past.slice(0, -1));
setFuture([{ draft, rows, pending }, ...future]);
restore(prev);
};
const redo = () => {
const next = future[0];
if (!next) return;
setFuture(future.slice(1));
setPast([...past, { draft, rows, pending }].slice(-HISTORY));
restore(next);
};
const patch = (next: Partial<CmsPageDraft>) => {
step(`page:${Object.keys(next).join()}`);
setDraft((d) => ({ ...d, ...next }));
};
const setTitle = (title: string) => {
step("page:title");
setDraft((d) => withTitle(d, title));
};
/**
* A super admin's new page changes company: FORM blocks and hero sign-up forms lose their event, which belongs to the old one,
* and a hero's form heading and text go with its form (add-hero-full-width).
*/
const changeCompany = (companyId: number) => {
step(null);
setDraft((d) => ({ ...d, companyId }));
setRows((rs) => rs.map((r) => {
if (!r.block.eventUuid) return r;
const { formHeading: _h, formText: _t, ...block } = r.block;
return { ...r, block: { ...block, eventUuid: null } };
}));
};
const setBlock = (key: number, update: (block: CmsBlock) => CmsBlock) =>
setRows((rs) => rs.map((r) => (r.key === key ? { ...r, block: update(r.block) } : r)));
/** A change from the block's fields (form or side panel). */
const updateBlock = (key: number, update: (block: CmsBlock) => CmsBlock) => {
step(`panel:${key}`);
setBlock(key, update);
};
/** A plain text field typed into on the canvas. */
const text = (key: number, path: string, value: string) => {
step(`${key}:${path}`);
setBlock(key, (b) => setField(b, path, value));
};
/** Rich text typed into on the canvas. */
const html = (key: number, value: string) => {
step(`${key}:html`);
setBlock(key, (b) => ({ ...b, html: value }));
};
/** Brings a section into view on the canvas: one just added, copied, moved, or refused by the server. */
const reveal = (index: number) => setRevealed((r) => ({ index, n: (r?.n ?? 0) + 1 }));
const moveBlockTo = (from: number, to: number) => {
if (from === to) return;
step(null);
setRows((rs) => moveItem(rs, from, to));
setSelected((s) => (s === from ? to : s));
reveal(to);
};
const moveBlock = (index: number, delta: -1 | 1) => moveBlockTo(index, index + delta);
const removeBlock = (key: number) => {
step(null);
setRows((rs) => rs.filter((r) => r.key !== key));
setPending(({ [key]: _dropped, ...rest }) => rest);
setSelected(null);
};
/** A new block of that type at that place, selected. */
const insertBlock = (at: number, type: BlockType) => {
step(null);
setRows((rs) => [...rs.slice(0, at), { key: ++nextKey.current, block: emptyBlock(type) }, ...rs.slice(at)]);
setSelected(at);
reveal(at);
};
const addBlock = (type: BlockType) => insertBlock(rows.length, type);
/** A copy of the block below it, selected; a chosen image not saved yet goes with it. */
const duplicateBlock = (index: number) => {
const row = rows[index];
if (!row) return;
step(null);
const key = ++nextKey.current;
setRows((rs) => [...rs.slice(0, index + 1), { key, block: structuredClone(row.block) }, ...rs.slice(index + 1)]);
if (pending[row.key]) setPending((p) => ({ ...p, [key]: p[row.key] }));
setSelected(index + 1);
reveal(index + 1);
};
/** A Custom HTML block whose canvas frame does not show its current HTML: changed or moved since the last save. */
const stale = (index: number) => {
const row = rows[index];
if (row?.block.type !== "HTML") return false;
const saved = savedHtml[row.key];
return draft.id == null || !saved || saved.index !== index || saved.html !== row.block.html;
};
const chooseImage = (key: number, file: File) => {
step(null);
setPending((p) => ({ ...p, [key]: { file } }));
readDataUrl(file)
.then((preview) => setPending((p) => (p[key]?.file === file ? { ...p, [key]: { file, preview } } : p)))
.catch(() => {});
};
function showError(err: unknown) {
const data = err instanceof ApiError ? (err.data as { code?: string; details?: { field?: string } } | undefined) : undefined;
const field = data?.details?.field;
const message = data?.code ? t(data.code) : t("PagesSaveFailed");
if (field) setErrors({ [field === "file" ? "blocks" : field]: message });
else setSummary(message);
// The on-page editor selects the refused block and brings it into view; a page field shows in the page settings.
const block = field?.match(/^blocks\[(\d+)\]/);
if (block) {
const index = Number(block[1]);
setSelected(index);
reveal(index);
} else if (field) setSelected(null);
}
async function save(): Promise<boolean> {
setSummary(null);
setNotice(null);
setErrors({});
if (isNew && isSuper && !draft.companyId) {
setErrors({ companyId: t("ChooseCompany") });
return false;
}
setSaving(true);
const next = rows.map((r) => ({ ...r }));
const left = { ...pending };
try {
for (const row of next) {
if (!left[row.key]) continue;
const data = (await readDataUrl(left[row.key].file)).split(",")[1];
row.block = { ...row.block, imageId: (await uploadPageImage(draft.companyId, data)).id };
delete left[row.key];
}
const page = await savePage(draft.id, pageBody({ ...draft, blocks: next.map((r) => r.block) }));
setDraft((d) => ({ ...d, id: page.id, companyId: page.companyId }));
setSaved({ slug: page.slug, status: page.status });
setHasDraft(!!page.draft);
if (page.draft) setRevealDraft((n) => n + 1);
setDirty(false);
remember(next);
setNotice("PagesSaved");
if (isNew) router.replace(`/pages/${page.id}?saved=1`);
return true;
} catch (err) {
showError(err);
return false;
} finally {
// Uploaded images stay on their blocks and leave the pending set, success or not.
setRows(next);
setPending(left);
setSaving(false);
}
}
/** Saves the current edits, then makes the draft live. */
async function publishChanges() {
if (draft.id == null || !(await save())) return;
setSaving(true);
try {
show(await publishPage(draft.id));
setNotice("PagesChangesPublished");
} catch (err) {
setNotice(null);
showError(err);
} finally {
setSaving(false);
}
}
async function discardChanges() {
if (draft.id == null) return;
setSaving(true);
setSummary(null);
setErrors({});
try {
show(await discardPage(draft.id));
setNotice("PagesChangesDiscarded");
} catch (err) {
showError(err);
} finally {
setSaving(false);
}
}
/** Deletes the page and leaves for the list; false when refused. */
async function remove(): Promise<boolean> {
if (draft.id == null) return false;
setSaving(true);
try {
await deletePage(draft.id);
setDirty(false);
router.push("/pages");
return true;
} catch (err) {
showError(err);
return false;
} finally {
setSaving(false);
}
}
/** The refusals for one block, keyed by its own field path. */
const blockErrors = (index: number) => {
const prefix = `blocks[${index}].`;
return Object.fromEntries(Object.entries(errors).flatMap(([path, m]) => (path.startsWith(prefix) ? [[path.slice(prefix.length), m]] : [])));
};
return {
draft, rows, pending, saved, dirty, loading, loadError, errors, summary, notice, saving, hasDraft, revealDraft, events,
code, isNew, isSuper, companies: scope.companies, branding,
selected, select: setSelected, revealed, frameVersion, stale,
canUndo: past.length > 0, canRedo: future.length > 0, undo, redo, endTyping,
patch, setTitle, changeCompany, updateBlock, text, html, moveBlock, moveBlockTo, removeBlock, addBlock, insertBlock, duplicateBlock,
chooseImage, blockErrors,
save, publishChanges, discardChanges, remove,
};
}
Loaded 100 of 114 files, more files were not shown because too many files have changed in this diff. Show more