Skip to content

feat(widget): add sahajcloud live preview for region and event views - #54

Merged
Ardnived merged 14 commits into
mainfrom
feat/live-preview
Jul 16, 2026
Merged

Ardnived merged 14 commits into
mainfrom
feat/live-preview

Conversation

@Ardnived

@Ardnived Ardnived commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds PayloadCMS live preview for the Region and Event drawers. The SahajCloud admin opens the standalone Atlas at /preview?collection=…&id=…&secret=…; it renders the full widget — map and drawer — for the doc being edited (including unpublished draft events) and updates live as the editor types, without saving or reloading.

  • Preview is boot session-state (only ever the standalone /preview iframe, never the web-component), held in a config/preview.ts singleton — not a WidgetMode axis. The controller is lazy-loaded, so normal standalone/embedded use pays nothing.
  • The controller renders no drawer of its own — it seeds the existing ['event', id] / ['region', slug] query cache from the live doc and drives the URL, then the normal resolveStack / DrawerStack / EventView / RegionView machinery renders it. Links are inert (except same-page #hash), navigation is pinned to the doc (+ register/share), and the registration submit is disabled so previewing a draft can't create a real registration.

How it works

  • Boot — main.tsx detects /preview, captures collection/id/secret into the singleton, and history.replaceStates the secret out of the address bar before React mounts. 'preview' joins RESERVED_SLUGS.
  • Draft fetch — the shared request interceptor (client.ts) adds draft=true + the x-sahajcloud-preview-secret header while preview is active.
  • Live updates — a ~20-line hand-rolled transport (ready handshake + origin-locked payload-live-preview listener) pushes each edit through Payload's populate endpoint using our own API-key + secret (populatePreviewDoc) — no dependency, no credentialed round-trip. The server resolves relations + computed fields (upcomingDates, image urls); the widget always gets a complete, valid doc over plain CORS.

Companion (CMS) dependency

Verification

  • lint ✓, typecheck ✓, 240 unit tests ✓, build ✓ — PreviewController is a code-split ~2.9 kB chunk, so the feature adds nothing to the main bundle.
  • Driven end-to-end in the browser against a local SahajCloud: draft event/region boot + map framing, secret stripped from the URL, links inert, register opens/closes with the submit disabled, and a live title edit propagates while schedule + relations are preserved. (Runtime testing also caught + fixed a navigation snap-back bug.)

Notes

  • Merged main (region-hierarchy / event-feed spike perf(api): spike — separate the region hierarchy from the event feed #53): the preview region code now uses the RegionNode model + wholesale region tree (getRegionNodeById).
  • Accepted limitations (per the issue): an unpublished event contributes no cluster dot (the selection pin + framing still work from the doc's coordinates); a brand-new unsaved doc shows a "save first" fallback; a mid-edit image/relation change previews after save + reopen (scalars/schedule preview live).

Closes #40

🤖 Generated with Claude Code

Ardnived and others added 11 commits July 14, 2026 15:06
Third runtime axis alongside standalone/hasMap, defaulting false and
threaded App -> AppShell -> WidgetModeContext. Only the /preview boot
sets it; embedded/standalone use is unchanged and zero-cost.

Part of #40

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Add config/preview.ts, an in-memory session singleton (mirroring
config/api/auth.ts) populated at boot from
/preview?collection=&id=&secret=. main.tsx captures it before React
mounts and scrubs the secret from the address bar via replaceState;
'preview' joins RESERVED_SLUGS so the boot pathname never resolves as a
region slug and the home-region redirect (fires only on '/') stays
dormant.

Part of #40

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
When the preview session is active and carries a secret, the shared
request interceptor adds the x-sahajcloud-preview-secret header and
draft=true to every SahajCloud read. This unlocks draft docs, exempts
the request from the client select/populate gate, and bypasses the read
cache. Gated on an active session so normal traffic is untouched.

Part of #40

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Pull getEvent's post-parse shaping (image-URL resolution + path
derivation) into an exported shapeEventDoc(doc). Pure refactor — getEvent
is unchanged behaviourally — so live preview can reuse the identical
shaping on docs pushed over the postMessage stream.

Part of #40

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Add src/lib/preview: mergePreviewData (ported from WeMeditateWeb) keeps
last-known-good populated relations when a live message collapses them to
bare IDs, while letting real edits through; shouldBlockPreviewLink and
allowedPreviewPaths are the pure predicates behind the link guard and
route lock. All pure/node-tested; the React wrappers live in the
controller.

Part of #40

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The lazy-loaded controller (mounted from AppShell only in preview mode)
drives the drawer cache + map camera from the live doc without rendering
a drawer of its own:

- boot-fetches the raw doc by id (getEventDoc / getRegionDocById), then
  navigates to its canonical path so the normal resolveStack/DrawerStack
  renders map + drawer unchanged
- useLivePreview streams edits; events merge-guard + shapeEventDoc +
  setQueryData(['event', id]); regions overlay editable scalars onto the
  cached shaped Region (counts/bounds/lists are geojson-derived)
- capture-phase link guard inerts every anchor except same-page #hash;
  a route lock snaps back if navigation leaves the allowed set
- a "save first" fallback for a brand-new unsaved doc

Adds @payloadcms/live-preview-react (3.x, matching the CMS), code-split
into its own chunk so normal standalone/embedded use pays nothing.

Part of #40

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Previewing a draft event opens the registration drawer, but the submit
is disabled and the mutation short-circuited (Enter-key submit included),
so a preview session can never create a real registration against a
draft event.

Part of #40

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The per-doc boot effect navigated to previewPath with `navigate` in its
deps; react-router recreates `navigate` on every navigation, so opening
register/share re-fired the boot hop and immediately snapped the route
back to the event. Fold the boot navigation into the route lock, which
navigates only when the path leaves the allowed set — a no-op on
register/share. Caught in runtime preview verification.

Part of #40

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
- hoist the shared region-doc select into REGION_DOC_SELECT so getRegionDoc
  and getRegionDocById can't drift
- export regionRoute and reuse it for the region preview path instead of
  re-deriving safePath(webPath) ?? /slug
- cross-reference resolveStack from allowedPreviewPaths

Part of #40

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Two code-review findings:
- the route lock compared the percent-encoded location pathname against
  the decoded allowed set, so an accented slug (/li%C3%A8ge/...) snapped
  back on every navigation; compare via isCanonicalPath (decoded).
- the drawer's suspense query is stale under the global staleTime of 0,
  so it background-refetched on remount and stomped unsaved live edits
  with the last-saved doc; pin event/region freshness while previewing.

Part of #40

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Skip __proto__/constructor keys in the overlay loop. Belt-and-suspenders
(the overlay is origin-validated CMS output, re-validated by zod), but
cheap and correct for a merge that walks wire data.

Part of #40

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Ardnived and others added 3 commits July 14, 2026 17:38
Preview is boot session-state (only ever the standalone /preview iframe,
never the web-component), not an embedding/render mode like
standalone/hasMap — and the config/preview.ts singleton is already the
source of truth (the interceptor and controller read it). Remove the
redundant WidgetMode.preview flag and its App -> AppShell -> context
prop-threading; the two consumers (the controller mount gate and the
registration submit disable) read preview.active directly, mirroring
config/api/auth.ts. Behaviour-identical.

Part of #40

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The @payloadcms/live-preview-react hook re-populates relations via a
credentialed, admin-cookie round-trip that (a) doesn't match Atlas's
API-key auth and (b) is blocked cross-origin, handing back bare-id
relations that mergePreviewData then had to defend against. We were
fighting the library.

Replace it with the trivial live-preview transport hand-rolled (~20 lines:
ready handshake + origin-locked message listener) and push each edit
through the CMS populate endpoint with our own API-key + secret
(populatePreviewDoc). The server resolves relations + computed fields
(upcomingDates, image urls) and unlocks drafts, so the widget always
gets a complete, valid doc over plain CORS — only #575's header
allow-list is needed, no credentialed round-trip.

Drops the dependency, merge.ts + its tests, and the __proto__ guard
(PreviewController chunk 4.9 -> 2.9 kB). More robust: live edits are now
verified end-to-end, preserving schedule/register/relations. Regions
re-populate the same way and overlay their scalars.

Part of #40

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Resolve API-layer conflicts from the #53 region-hierarchy / event-feed
split:
- adopt main's RegionNode model + wholesale getRegions() tree; migrate the
  live-preview region-by-id read to getRegionNodeById (looks the node up in
  the cached tree instead of a per-region fetch) and PreviewController from
  RegionDoc -> RegionNode.
- keep regionRoute exported for the preview controller.
- fetch.test.ts: keep the shapeEventDoc import, drop the now-removed
  toSahajLocale; shorten a preview-secret test fixture so the merged-in
  security-scan hook doesn't false-positive on it.

client.ts auto-merged. Gate green: lint + typecheck + 240 tests + build.
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jul 16, 2026 •

Copy link
Copy Markdown

Deploying sahajatlas with  Cloudflare Pages  Cloudflare Pages

Latest commit: e5daec3
Status: ✅  Deploy successful!
Preview URL: https://049236f1.sahajatlas.pages.dev
Branch Preview URL: https://feat-live-preview.sahajatlas.pages.dev

View logs

@cloudflare-workers-and-pages

Copy link
Copy Markdown

Deploying sahajatlas-design with  Cloudflare Pages  Cloudflare Pages

Latest commit: e5daec3
Status: ✅  Deploy successful!
Preview URL: https://4d656667.sahajatlas-design.pages.dev
Branch Preview URL: https://feat-live-preview.sahajatlas-design.pages.dev

View logs

@Ardnived
Ardnived merged commit 877d551 into main Jul 16, 2026
4 checks passed
@Ardnived
Ardnived deleted the feat/live-preview branch July 16, 2026 22:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(widget): add sahajcloud live preview for region and event views

1 participant