Repository navigation
fix(ui): scope widget css so it cannot restyle the host page - #113
Merged
Merged
Conversation
The stylesheet is injected into the HOST document, after its own sheets, so anything left at top level wins ties and repaints somebody else's site: Tailwind's Preflight, every generated utility (`.container` included), the `:root`/`.dark` palette blocks, and the whole of mapbox-gl / swiper / vaul / Radix Colors. Hand-scoping was the rule and it had already leaked twice, because a leak is invisible to lint, typecheck and the unit lane. So the invariant is mechanical now. A PostCSS pass runs last and confines every selector to `.sy-atlas` — the class on the theme root — mapping the root-addressing ones (`:root`, `html`, `body`, a bare `.dark`) onto that element rather than under it, and wrapping combinator selectors in `:is()` so the scope element can satisfy the `.dark` / `[dir]` half of a variant itself. `@keyframes` are namespaced too: the names are document-global and last-definition-wins, so our bare `fadeIn` was overriding host animations. `scripts/assert-css-scoped.mjs` reads the CSS back out of the built bundle and fails the build on any selector that escapes. Raleway is self-hosted, dropping a runtime Google Fonts `@import` that disclosed every visitor's IP (LG München I, 3 O 17493/20) and forced two origins into every host CSP. The face is registered from TypeScript, not CSS: a `url()` in an injected stylesheet resolves against the HOST's origin, so the URL has to be resolved at runtime against `import.meta.url`. Inlining it as base64 instead measured +216 KB gzipped on the eager payload. Closes #91 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Both came out of measuring a representative host page's computed styles with
and without the widget, cross-origin, rather than reading the built CSS.
1. vaul injects its OWN stylesheet at import time (`__insertCSS` at module
scope in its dist) — raw, unscoped, and never seen by the build's scoping
pass. It defines bare `@keyframes fadeIn` / `fadeOut` / `slideFrom*`, and
keyframe names are document-global and last-definition-wins, so it hijacked
the host page's own `fadeIn` (the harness element visibly changed opacity;
Animate.css ships that exact name). We already vendor that identical CSS as
src/styles/vaul.css, which the pass scopes properly — so the patch neuters
the injection and nothing is lost.
2. The scope prefix is now `:where(.sy-atlas)` rather than `.sy-atlas`.
The bare class added one class of specificity to every rule including
Preflight, which then outranked CSS a library injects at RUNTIME — the pass
never sees that CSS, so it never lifts to match. Measured: scoped Preflight
`input { padding: 0 }` (0,1,1) beat the Mapbox geocoder's own
`.mbx…--Input { padding: 0 40px }` (0,1,0) and the search icon sat on top of
the placeholder. `:where()` is specificity-zero, so every rule keeps exactly
the weight it had and only its REACH narrows — which is all this is for.
Host page after both: 0 changed properties across 18,050 computed-style
comparisons on 38 elements.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
README: hosts no longer need fonts.googleapis.com / fonts.gstatic.com (the typeface is self-hosted), they need font-src for the widget's own origin, and there is now a plain statement that the widget will not restyle their page. components.md: the scoping rule was hand-discipline and had leaked twice. It is mechanical now, so the rule says what the pass covers — and, more usefully, the three things it does NOT: the `.sy-atlas` pass-through escape hatch, CSS a library injects at runtime, and why the prefix must stay `:where()`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
- The Mapbox geocoder's theme still asked for `Raleway`, a family that stopped existing when the face was renamed — its input was silently falling back to the system sans. FONT_FAMILY is exported and the stack is built from it. - One seam for the scope class: `applyTheme` already owns the theme root and is the path both standalone and Ladle take, so it applies the class. The Ladle effect is gone, and the drift test now asserts the seam rather than grepping three files for a token. - Plugin: use postcss-selector-parser's own `isPseudoElement`/`isCombinator`, hoist the parser and memoize the scoped-selector pattern (both were rebuilt per selector, thousands of times per build, on every dev CSS edit), and drop the unreachable second already-scoped check. - Assertion script: scan for the closing backtick instead of concatenating ~300k single characters, unescape in one pass, skip the byte-identical second copy of the sheet, resolve dist/ from the module rather than the cwd, and take the rule count from assertScoped instead of a third walk. - THEME_CLASSES is exported and pinned against the classes applyTheme writes, and fonts.ts exposes a pure `fontFaceCss()` so the one stylesheet that skips the scoping pass is asserted rather than promised in a comment. Kept: the separate transform/verify walks in the plugin (build-time only, and the belt-and-braces split is the point) and the post-build extractor over dist (asserting the bytes we actually ship is a stronger claim than asserting the string we handed the injector). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The high one was self-inflicted, from the previous commit's "one seam" cleanup:
putting the scope class in `applyTheme` looked right, but `getThemeRoot()` falls
back to `document.documentElement` and BrandTheme releases the module-level root
on unmount — so with two embeds on a page the survivor's next theme write would
stamp `sy-atlas` onto the HOST page's <html> and apply the whole widget
stylesheet to their site. Each owner applies the class to an element it actually
owns again, and a spec now pins that applyTheme does NOT.
Also from review:
- Preflight's `body { margin: 0 }` collapsed onto the scope, so standalone (where
the scope is <html>) kept the UA's 8px and a `100dvh` map-less page overflowed
the viewport by 16px. Restated as `.sy-atlas body`.
- The `:is()` wrap could strand a pseudo-element inside the wrapper
(`.a::before + .b`, `::-webkit-scrollbar-thumb:hover`) or leave a dangling
combinator. `:is()` is FORGIVING, so those parse fine and match nothing — a
silently dead rule, this pass's own failure mode pointed inward. Qualifying
pseudo-classes now travel with their pseudo-element, and anything still
invalid throws. Checked on the AST: a text test for `::`/`before` fires on
Tailwind's own `.before\:…` variant classes.
- A keyframe named after an animation keyword (`@keyframes ease`) would have had
the wrong token rewritten in the shorthand; it fails loudly instead.
- Only a BARE `:host`/`:root` collapses — `:host(.theme)` kept its condition.
- Nested-rule detection walks the whole ancestor chain, not one level.
- The gate could pass while silently skipping a chunk (it only recognises a
template literal, which is a minifier artefact): it now cross-checks the sheets
it extracted against the injection-site count, fails on any stray .css asset,
and checks @font-face families, which no selector-based check can see.
- `_headers` covers `/locales/*` too — same CORS dependency, worse failure.
- README documents `style-src 'unsafe-inline'` and the two honest exceptions to
"will not restyle your page" (the modal scroll-lock, library font families).
- Font dep pinned exactly; its bytes ship to visitors.
Verified after: 0 changed properties across 18,050 computed-style comparisons on
the host page, host <html> untouched, and the standalone page back to margin 0
with no overflow.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Deploying sahajatlas-design with
|
| Latest commit: |
9a2524c
|
| Status: | ✅ Deploy successful! |
| Preview URL: | https://5a115bf9.sahajatlas-design.pages.dev |
| Branch Preview URL: | https://fix-scope-widget-css.sahajatlas-design.pages.dev |
Deploying sahajatlas with
|
| Latest commit: |
9a2524c
|
| Status: | ✅ Deploy successful! |
| Preview URL: | https://b157c353.sahajatlas.pages.dev |
| Branch Preview URL: | https://fix-scope-widget-css.sahajatlas.pages.dev |
Portalling the lightbox into the theme root (needed so the scoped stylesheet reaches it) cost YARL its own scroll lock: it works by putting .yarl__no_scroll on document.body, and that rule is now confined under the widget's scope class, which document.body sits outside. The class landed and matched nothing, so the page scrolled behind a full-screen overlay. Reapply the rule's three declarations inline while the lightbox is open, capturing and restoring each so a host's own inline styles survive. Closes #91 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Ardnived
added a commit
that referenced
this pull request
Aug 7, 2026
Two conflicts, both keep-both: - CLAUDE.md — this branch rewrote the Routing row for the two-router mount, main rewrote Build tool + Data in the same table. Kept all three. - src/Widget.tsx — this branch restructured the wrapper (lang, role, the hash/memory branch), #113 added WIDGET_SCOPE_CLASS to its className. Kept the restructure and carried the scope class onto it: without that class the embed renders entirely unstyled. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
This was referenced Aug 7, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
<head>(no shadow DOM), but every selector in it is now confined to the widget's own subtree and every@keyframesname is namespaced — enforced mechanically at build time, not by discipline.@importoffonts.googleapis.comis gone, taking a GDPR exposure (LG München I, 3 O 17493/20) and two forced CSP origins with it. Cost to the eager payload: +0.4 KB gzipped.Measured, cross-origin
A host page with its own typography, links, lists, blockquote, form controls, a
.container, an element withclass="dark", its own Swiper, and its own@keyframes fadeIn— served from one origin, the built widget embedded from another:@keyframesshipped¹ the host's own
fadeInanimation was being hijacked; the Preflight/utility leak was live in the CSS but this harness measures the observable delta.Changes
scripts/postcss-scope-widget.mjs— runs last in the PostCSS chain, so it sees Tailwind's output and the third-party sheets Vite inlined. Rewrites selectors to:where(.sy-atlas) …, collapses root selectors onto the scope element, compounds bare theme classes, wraps combinator selectors in:is(), namespaces@keyframes.scripts/assert-css-scoped.mjs— reads the CSS back out of the built bundle and failspnpm buildon any escape. CI and the Cloudflare build both gate on it.patches/[email protected]— vaul calls__insertCSSat module scope, injecting its raw stylesheet (bare@keyframes fadeIn) into the host document. We already vendor that CSS assrc/styles/vaul.css, which the pass scopes, so the injection is neutered.src/styles/fonts.ts— registers the faces from TS, not CSS: a CSSurl()resolves against the host's origin, so/assets/…woff2would 404 on every embed.new URL(url, import.meta.url)resolves against our chunk instead.src/components/molecules/ImageCarousel/lightbox.tsx— the last overlay still portaling todocument.body, where scoped CSS can't reach it.Verification
ladle:build✓<html>never receives the scope class; one font request, to our own origin, latin subset only.sy-atlas-slideFromBottom), carousel bullets,.colored-linksprose, Mapbox geocoder + map.?map=0):bodymargin 0, no overflow.Notes for reviewer
Why
:where()and not a bare.sy-atlas. A bare class adds one class of specificity to every rule including Preflight, which then outranks CSS a library injects at runtime — the pass never sees that CSS, so it never lifts to match. It broke the Mapbox geocoder (scoped Preflightinput { padding: 0 }beat.mbx…--Input { padding: 0 40px }; the search icon landed on the placeholder).:where()is specificity-zero, so the cascade inside the widget is unchanged and only each selector's reach narrows. Please don't "simplify" it away — there's a spec pinning it.Deliberately not done: the font is linked rather than base64-inlined (inlining measured +216 KB gz — the injector emits the whole sheet twice per build entry); Preflight stays enabled (scoping it preserves the look and still shields the widget); the duplicate CSS injection is left alone (
relativeCSSInjection: falseleaves the standalone entry with no CSS — worth its own ticket); the lightbox's host-page scroll lock is now inert in an embed, which is the direction this ticket wants.Reviews: a code review and a security review both caught a high-severity issue an intermediate cleanup had introduced — writing the scope class inside
applyTheme, whose root falls back todocument.documentElement, could have stamped the class onto the host page's<html>and applied the whole stylesheet to their site. Reverted, with a spec pinning that it must not.sign_and_send_pubkey: signing failed), so signing was disabled and the branch pushed over the gh HTTPS credential helper. Re-sign with:git rebase --exec 'git commit --amend --no-edit -S' origin/mainImplementation report:
.claude/reports/91-scope-widget-css.md(gitignored, local).