Repository navigation
feat(widget): keep state when a host replaces the element - #383
Conversation
A Wix router page re-renders on Back/Forward, destroying `<sahaj-atlas>` and creating another element carrying the same configuration. `connectedCallback` read that as a different element arriving inside the teardown grace window and ran the release, which clears the query cache and the API key — so every press cost a full re-read of the feed, the region tree and the client record. The release exists for one reason, stated at `TEARDOWN_GRACE_MS`: only `['client', apiKey]` carries the credential in its key, so an element re-added under a DIFFERENT key would read the first key's responses out of the cache. That reason is the condition now. Under the same key ownership transfers and the cache stays; a different key keeps today's release. The Mapbox instance needed no work: `reuseMaps` is already set on `<ReactMapGL>`, and react-map-gl recycles the map on unmount and reparents its canvas into the next container, whichever root that is. `docs/embedding.md` gains the pointer to SahajCloud's Install tab, the Wix Custom Element track, and what does and does not survive a replacement. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjVCYjgUifyqdH1rrEQ
…makes Three restatements the reuse pass found. The Wix section re-argued why a sandboxed frame costs the shareable, indexable route, which "Which one, and what you give up" already owns, and re-stated the height rule the Sizing section owns — both now link instead. The changelog entry re-derived #149's behaviour from scratch, so a host could not tell what #349 changed; it names the delta against #149 now. A factual slip went with them: a page builder relocating the element is the SAME element coming back, which #149 already covered. Only a re-render puts a new element in its place. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjVCYjgUifyqdH1rrEQ
The review pass found a six-line block that restated the `TEARDOWN_GRACE_MS` docblock thirty lines above it and then narrated what the old behaviour cost. What stays is the part a reader cannot re-derive: why a new element and not only a returning one, what `owner !== this` buys once the key comparison is there, and a `shortcut:` line naming the limit this fix accepts — the cache is key-agnostic bar `['client', apiKey]` — with the trigger for lifting it. The ownership rule gained a term silently: `owner.isConnected` is now the only thing separating a replacement from a second embed on the page, which also makes removal-before-insertion part of the design. The `owner` docblock says both. In the spec, `vi.runOnlyPendingTimers()` replaces a 5s constant that would have stopped exceeding the grace window if it ever grew. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjVCYjgUifyqdH1rrEQ
|
🤖 no session running recent dispatchesWritten by the sydevs dispatcher. Sessions never edit this comment. |
Deploying with
|
| Status | Name | Latest Commit | Updated (UTC) |
|---|---|---|---|
| ✅ Deployment successful! View logs |
sahajatlas-design | 1ca56c8 | Nov 11 2026, 06:12 PM |
|
🩹
It went bad between 18:01Z and 18:29Z today. Green on A re-run repeats the upload and fails the same way. Someone has to mint a Workers-scoped token and reset the secret. Nothing on this branch changes. It is level with 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
sydevs-bot
left a comment
There was a problem hiding this comment.
🧐 Adversarial review
The diff is smaller than the ticket and does the job: one condition in connectedCallback, no new file, helper, constant or dependency, and the deeper fix declined with a shortcut: that names its trigger. Scope matches #349 — the CHANGELOG and the guide were both asked for, and the map half correctly turned out to need no code. The cross-repo claim holds: SahajCloud's Install tab exists (Clients.ts:481), and its Wix templates agree with the guide on Server URL, tag name, Premium plus domain, and the Velo router.
What this review does not accept is the new contract paragraph. The guide tells hosts three things do not survive a replacement, and all three appear to: the drawer stack is the URL, and the zustand stores are module singletons releaseOwnership never touches. That is host-facing copy, so settle it before the reviewer reads it.
Findings
- should-fix —
docs/embedding.md:145: the "what does not survive" list is wrong on all three items. - consider —
src/Widget.tsx:505: insertion before removal costs the whole widget, not one render.
What was checked
Ticket #349 and parent #348. The diff from the checkout. Read whole: Widget.tsx, config/embed.ts, config/api/auth.ts, config/store.ts, lib/shape/path.ts, lib/shape/navigation.ts, lib/atlas-history.ts, RegistrationForm.tsx, the new spec, both guide sections. Ladder: the diff adds no new piece to walk. Consumer side: SahajCloud InstallGuide/{steps,templates}.ts and Clients.ts against the Wix section; both CHANGELOG anchors resolve. The preview answers 200 now — Smoke went green on this head at 17:56, so the body's "does not resolve yet" line is stale rather than wrong.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
The guide told hosts three things are lost on a replacement, and all three come back. The drawer stack is a pure function of the pathname (`resolveStack`), the in-widget back depth is stamped into the browser's own history entry (`atlas-history`), and the registration draft is a module singleton the release never touches, re-seeded by event id. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjYrLvFd4922qDe5641
The docblock called the opposite order one lost render. It costs the page its whole widget: the arrival is refused while the old owner still stands, it gets no second connectedCallback, and the old owner's deferred teardown then leaves nothing running. Hosts need the ordering rule too, so the guide carries it. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjYrLvFd4922qDe5641
|
Both review threads adopted and resolved. Pushed as 1ca56c8.
Lean gate green: lint, typecheck, 2000 tests in 166 files. No code changed since the security review — Body refreshed: the contract outline, and the preview link, which answers 200 now. 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
#383 and this branch each added an entry at the head of CHANGELOG's Unreleased § Changed, so git saw an add/add there. Both entries stay, #392 above #349, which keeps the section newest-first. Nothing else overlapped: `docs/embedding.md` and `docs/testing.md` took both sides' new sections cleanly, and the code main brought touches `Widget.tsx`, which this branch never opens. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjZVTLRdTmG2ijYEpfj
Summary
<sahaj-atlas>and creates a new one under the same key now keeps the query cache and the API key, so a Wix Back/Forward press costs no SahajCloud reads. Measured in a browser: 5 reads before, 0 after.docs/embedding.mdgains the Install-tab pointer, a Wix Custom Element section, the remove-before-insert rule, and what a replacement does and does not carry across.Change outline
Behaviour —
connectedCallback, when an element arrives inside the teardown grace windowThe release exists so an element re-added under a different key cannot read the first key's responses out of the cache. That reason is now the condition.
connectedCallback() src/Widget.tsx pendingTeardown set? # something left < TEARDOWN_GRACE_MS ago clearTimeout; pendingTeardown = null - owner !== this → releaseOwnership() # clears queryClient, nulls apiKey + owner !== this && key changed → releaseOwnership() + owner !== this && key unchanged → fall through # the transfer: the cache stays owner === this → fall through # a move, as before owner && owner !== this && owner.isConnected → refuse, warn, render nothing owner = this adoptStyles(shadowRoot); super.connectedCallback() # unchangedThe key compared is
atlasAuth.apiKeyagainstembed.config.key: the first is the credential in force and so the cache's lineage, the second is what the arriving element would authenticate as.releaseOwnershipmoves both together, which is what makes the comparison sound.Contract —
docs/embedding.mdOne rule per line, paraphrased.
Preview
Nothing here is visible by opening a page. The change only shows when an element is replaced, so the reproduction below is the preview — it runs against any embed page, including production.
auto.js200). The last two pushes changed comments and prose only, so the bundle behind it is the one measured below.Paste this in the console on any page carrying the embed, once
data-sahaj-atlas-readyis on<html>:Reproduction
The widget's content should reappear at the same route. On
mainthe same snippet listsclients/me,events/geojson,regions,globals/sy-atlas-configandglobals/sy-atlas-translations.Test results
.claude/skills/pr-prep/check.sh— lint, typecheck, 2000 tests in 166 filessrc/Widget.replace.test.tsx), each watched red against its own defect — see Detailpnpm build(incl.assert:css,assert:maps) andpnpm size(embed 329.2 / 330 KiB, unchanged)Manual verification
Two things no lane here reaches.
https://sydevelopers.wixsite.com/atlas-spike-classic/aboutwith this PR's previewauto.js. The spike site is free, so the Custom Element itself cannot be exercised there — the ticket already schedules this for sahajayoga.ca's go-live.VITE_MAPBOX_ACCESSTOKENreaches a routine's checkout, so the map never loaded here and I could not measure it. Read off the installed source instead:reuseMapsis already set on<ReactMapGL>(src/components/organisms/Mapbox/Map.tsx), so react-map-glrecycle()s the map into a module-level pool on unmount andMapbox.reuse()reparents its canvas into the next container — whichever root that is. So the ticket's second bullet needed no code. Worth confirming in a browser that no second map load is billed.The data half is measured. Against the built embed in Chromium (
pnpm review:embed), with the five reads stubbed, replacing the element:mainclients/me,events/geojson,regions,sy-atlas-config,sy-atlas-translationsNotes for reviewer
resolveStack(lib/shape/path.ts) derives the drawer stack from the pathname,atlas-history.tsreads the depth back out of the browser's ownhistory.state, anduseRegistrationDraftis a module singletonreleaseOwnershipnever touches, re-seeded by event id inRegistrationForm.tsx. What a replacement really costs is the old element's React state — a scrolled list starts at the top.CHANGELOG.mdcarried the same sentence and is corrected with it.ownerdocblock. The opposite order does not cost one render: the arrival is refused while the old owner still stands, never gets a secondconnectedCallback, and the old owner's deferred teardown then leaves the page with no widget at all.replaceWithand a framework re-render both remove first.atlasAuth.apiKey, not a newownerKey. The review pass suggested a second module variable holding the key ownership was taken under. Declined:atlasAuth.apiKeyalready is that fact —AtlasBootclaims it andreleaseOwnershipnulls it, in the same pair of functions that ownowner— so a second copy would be one more invariant two call sites must keep true. The two differ only beforeAtlasBoot's first render, where the cache is empty and the outcome is the same either way.config/api/index.tsplus every cache-only reader and writer, and that class of change already shipped silently broken once (live preview wrote['region', slug]while the drawer read['region', slug, locale]). The accepted limit and its upgrade trigger are now ashortcut:line beside the condition.QueryClientper element was considered and is the opposite of the fix — it would die with the element on every Back press.owner.isConnectedquietly became load-bearing. Before, a different element always hit the release first, which nulledowner, so the duplicate guard below exited on its first term. Now that guard is the only thing separating a replacement from a second embed, which also makes removal-before-insertion part of the design. Theownerdocblock says both.vi.mock('@/styles/sheet', …)quotes a module it never loads, which buys that module a spec selection: editingsrc/styles/sheet.tsgoes 1.15 s → 2.85 s. The mock is needed because jsdom gives a fresh shadow root noadoptedStyleSheets. Editingsrc/Widget.tsxis 3.3 s at 7 specs, and the widest selection in the tree is unchanged at 20, sodocs/testing.md's 12-second budget and its ceiling both hold.src/Widget.tsxmatchessecurityReview.triggerPattern. It checked whether the transfer can serve key-A data under key B (it cannot —bootis unreachable from host script, and the cache's lineage is the credential the release nulls), every reachable null-key state, and whether skippingreleaseAnnouncementleaves a false attestation (the marker disclaims forgery resistance by its own contract, and every mount republishes it). Everything pushed since is comments and Markdown —comment-fingerprint.mjsreports the code hash unchanged.Detail
The browser measurement.
pnpm build && pnpm review:embed, then Chromium against/__review/sidebar-mapless.htmlwithclients/me,events/geojson,regions,sy-atlas-configandsy-atlas-translationsfulfilled, waiting for the shadow root, thenold.replaceWith(document.createElement('sahaj-atlas')). Run twice: once on this branch, once with the condition reverted toowner !== thisand rebuilt. The script is throwaway and is not in the diff.The three spec cases, and the defect each one caught.
docs/testing.mdrequires watching a new assertion fail at the site that causes it, so each was run against a separate injected defect, before and again after the comment pass:owner !== thisalone — the behaviour onmaindisconnectedCallbacknot scheduling the teardownWhy the spec drives the real custom element. The decision is a lifecycle callback, so
renderToStaticMarkupreaches none of it. jsdom perdocs/testing.md's opt-in.@/Appis stubbed so the data layer never boots, which holds the file at 69 ms of test time.Declined, with the reviewer's own reason. The
vi.mock('@/App')factory and the rejectingfetchstub are byte-identical tosrc/Widget.path-boot.test.tsx's. Two copies is below this repo's extraction threshold,src/test-support/holds no mount helper, andvitest.config.tsdeclares nosetupFiles, so a per-file local helper is the established convention (Widget.theme-root.test.tsx,sheet.adopt.test.ts).Also declined:
pendingTeardown = nullbesideclearTimeoutis redundant only on the branch that callsreleaseOwnership; on the transfer branch it is the only thing that clears it, and hoisting it is what let the oldelsego — one branch where there were two.Blocker.
sydevs/SahajCloud#1055closed withsydevs/SahajCloud#1058, so the Install tab the guide points at is live. The pointer names/adminand the tab rather than a deep link, since the record id is per client.Closes #349