This document defines the current Vanilla Extract (VE) architecture for this repository. All new Bootstrap-to-VE component conversions should follow this approach.
Implementation: ve-project2/
Companion documents:
docs/ve2-migration-playbook.md— quick-reference playbook for converting a Bootstrap component family to ve-project2 (start here for a new conversion task).docs/ve2-theme-generator.md— automated generation ofve-project2/src/themes/{theme}/**from screenshot CSS artifacts.docs/ve2-literal-conversion-plan.md— implementation plan (v2) for the deterministic 1:1 literal converter (zero-mismatch, all 27 themes; includes the Bootstrap-JS integration spec for modals/dropdowns/carousels/etc.).docs/ve2-debugging-mismatch-walkthrough.md— step-by-step walkthrough for diagnosing screenshot mismatches using Playwright computed-style comparison (use this when a diff image is not enough to identify the root cause).docs/ve-architecture-v1-history.md— archived architecture of the first VE sub-project (ve-project), preserved as historical context.docs/ve-project1-docs-index.md— index of all historical docs for ve-project (v1).
The element-owned scope model removes two problems that plagued ve-project (v1):
- No global element styling. Nothing styles bare elements (
body,h1,button, etc.) globally. Every visual rule is opt-in, applied through explicit class composition. - No implicit ancestor/descendant matching. Theme styles never rely on a parent carrying a scope class and bare descendants inheriting from it. Every styled element carries both the scope class and the contract class directly, producing a compound selector with no space in between (
.scope.contract). Source combinators (>,+,~, descendant space) are still preserved when present, but each named segment re-asserts${scope}${contract}— e.g..card > .card-header→`${scope}${card} > ${scope}${cardHeader}`(see Literal converter selector model below).
This means unlimited nesting depth, zero specificity conflicts, and full theme overridability without @layer or extra selectors.
One empty style({}) export per theme. The class name is a stable hashed identifier generated by Vanilla Extract. It acts as a namespace prefix for all CSS rules belonging to that theme.
// ve-project2/src/themes/bootstrap/scope.css.ts
export const bootstrapScope = style({})The scope class itself remains zero-style; global vars are assigned via globalStyle(scope + varsContract, { vars: ... }).
One empty style({}) per component slot (button base, button primary variant, body, bodyText, etc.). Contract classes live in theme-contract/ and are shared by all themes.
// ve-project2/src/theme-contract/ui/buttons/contract.css.ts
export const btn = style({})
export const btnPrimary = style({})
// …// ve-project2/src/theme-contract/theme-contract.css.ts
export const vars = style({}) // root --bs-* custom-property host
export const body = style({}) // outer wrapper: background, padding, display
export const bodyText = style({}) // text root: font-family, font-size, colorAgain, no CSS properties embedded — only stable hashed class names.
All visual styling lives in globalStyle calls that target a compound selector (scope + contract with no space). This means the rule fires only on an element that carries both classes simultaneously.
// ve-project2/src/themes/bootstrap/ui/buttons/styles.css.ts
import { globalStyle } from '@vanilla-extract/css'
import { btn, btnPrimary } from '../../../../theme-contract/ui/buttons/contract.css'
import { bootstrapScope } from '../../scope.css'
globalStyle(`${bootstrapScope}${btn}`, {
display: 'inline-block',
padding: '0.375rem 0.75rem',
// …
})
globalStyle(`${bootstrapScope}${btnPrimary}`, {
color: '#fff',
backgroundColor: '#0d6efd',
borderColor: '#0d6efd',
})Root/body-level rules follow the same pattern, using body/bodyText contract classes:
// ve-project2/src/themes/bootstrap/scope.css.ts
import { globalStyle, style } from '@vanilla-extract/css'
import { body, bodyText, vars } from '../../theme-contract/theme-contract.css'
export const bootstrapScope = style({
})
globalStyle(`${bootstrapScope}${vars}`, {
vars: {
[varBsPrimary]: '#0d6efd',
// ... theme root --bs-* vars
},
})
globalStyle(`${bootstrapScope}${bodyText}`, {
fontFamily: 'system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',
fontSize: '1rem',
fontWeight: 400,
lineHeight: 1.5,
color: '#212529',
})
globalStyle(`${bootstrapScope}${body}`, {
// Direct body-level traits only (layout/background)
backgroundColor: '#fff',
padding: '1rem',
display: 'block',
})A SolidJS context that propagates the active scope class string to every descendant component. Components read it and stamp it on every element they render alongside their contract classes.
// ve-project2/src/context/ThemeContext.ts
import { createContext } from 'solid-js'
export const ThemeContext = createContext('')The same module also re-exports VE2 runtime typing and the request hook used by leaf components when granular style loading is enabled:
import { ThemeContext, type Ve2StyleFamily, useVe2RequiredStyleFamilies } from '../../../context/ThemeContext'Every rendered element carries both the scope class (from context) and its contract class(es):
// ve-project2/src/components/ui/buttons/solid/SolidPrimaryButton.tsx
const theme = useContext(ThemeContext)
<button type="button" class={`${theme} ${vars} ${btn} ${btnPrimary} pwhook-btn`}>
Primary
</button>The resulting CSS selector is .bootstrapScope_xyz.btn_abc { … } — no ancestor matching, no inheritance dependency.
A small wrapper component that stamps scope + vars + body + bodyText on a <div>, activating root theme vars plus typographic and layout rules for a themed subtree.
const ThemedBody: Component<{ children: any }> = (props) => {
const theme = useContext(ThemeContext)
return <div class={`${theme} ${vars} ${body} ${bodyText}`}>{props.children}</div>
}Use ThemedBody at the root of any themed region and whenever the theme switches in nested ThemeContext.Provider blocks.
ve-project2 now uses a runtime wrapper shell that keeps the legacy full-theme mode as default, while supporting opt-in granular family loading.
Ve2ShellRuntimechooses mode from URL query:- default mode: full-theme
Ve2Shell - granular mode:
?style-loader=granular(or?styleLoader=granular) usesVe2GranularShell
- default mode: full-theme
Ve2GranularShellstill provides the sameThemeContextscope class, but loads style families on demand via dynamic imports and dedupe caches.- If a route is not mapped to known granular families,
Ve2GranularShellfalls back to loading the full theme bundle for that theme.
// ve-project2/src/components/shell/Ve2ShellRuntime.tsx
return useGranularStyleLoaderEnabled() ? (
<Ve2GranularShell>{props.children}</Ve2GranularShell>
) : (
<Ve2Shell>{props.children}</Ve2Shell>
)Leaf components can declare their required style families and request them from the active shell using a no-op-safe hook (safe under full-theme shell, active under granular shell).
export const ve2RequiredStyleFamilies: readonly Ve2StyleFamily[] = [
'ui/buttons',
'contents',
'utilities',
]
const theme = useContext(ThemeContext)
useVe2RequiredStyleFamilies(ve2RequiredStyleFamilies)ve-project2/src/
theme-contract/
theme-contract.css.ts ← body, bodyText root contract classes
contents/
contract.css.ts ← h1…h6, paragraph, horizontalRule generic contents element contracts
ui/
buttons/
contract.css.ts ← btn, btnPrimary, btnSecondary, … contract classes
…/
contract.css.ts ← contract classes for each family
themes/
bootstrap/
scope.css.ts ← bootstrapScope (empty), + globalStyle scope+vars and body/bodyText rules
contents/
styles.css.ts ← globalStyle rules: bootstrapScope + h1/h2/…/paragraph/horizontalRule
ui/
buttons/
styles.css.ts ← globalStyle rules: bootstrapScope + btn/btnPrimary/…
…/
styles.css.ts ← globalStyle rules for each family
sketchy/
scope.css.ts ← sketchyScope (empty), + globalStyle scope+vars and body/bodyText rules
fonts.generated.css ← generated once at theme creation; @import rules for Google Fonts (sourced from screenshots/sketchy/theme.css)
contents/
styles.css.ts ← globalStyle rules: sketchyScope + h1/h2/…/paragraph/horizontalRule
ui/
buttons/
styles.css.ts ← globalStyle rules: sketchyScope + btn/btnPrimary/…
context/
ThemeContext.ts ← active scope context + VE2 request hook/type re-exports
components/
shell/
Ve2Shell.tsx ← legacy full-theme shell
Ve2GranularShell.tsx ← granular family-loading shell with fallback
Ve2ShellRuntime.tsx ← runtime switch: full vs granular
poc/
PocThemeScopeDemo.tsx ← interactive demo of element-owned scope
ui/
buttons/
solid/
SolidPrimaryButton.tsx ← leaf route component
… ← other button variants
index.tsx ← SolidJS router + explicit route wiring
-
Scope and contract classes must be empty
style({})— no CSS properties embedded. -
All styling goes through
globalStyle(scope + contract, props)— compound selector with no space. -
No global element selectors (
body,button,h1, etc.). -
Use
createVar()andvars:to mirror Bootstrap's CSS custom-property structure. Component-level vars (--bs-badge-padding-x, etc.) live intheme-contract/ui/{family}/_vars.css.ts. Global vars (--bs-border-radius,--bs-primary, etc.) live intheme-contract/_vars.css.tsand are assigned on${scope}${vars}so all descendants inherit them via CSS cascade. - Every styled element carries both the scope class and its contract class(es).
-
Root theme vars and body/text styles use dedicated root contracts:
varshosts global--bs-*, whilebody/bodyTextdefine layout and typography. -
Only these static class names are allowed in component markup:
bd-example-ve2,pwhook-*screenshot hooks. All other styling comes from VE imports. -
ThemeContext provides the active scope class string. Components read it via
useContext(ThemeContext)— no prop-drilling. -
Leaf components should declare family requirements with
ve2RequiredStyleFamiliesand calluseVe2RequiredStyleFamilies(...). Under full-theme shell this is a safe no-op; under granular shell it drives on-demand family loading. -
Ve2ShellRuntimeis the entry shell. Default behavior remains full-theme loading; granular mode is opt-in through query param. - Granular mode must always preserve a safe fallback path. If a route is outside known family mappings, load the full theme chunk once for that theme.
-
ThemedBody(or equivalent) must wrap any region that requires body-level theme styles (font, color, background). -
Each theme must be implemented as a self-contained source of truth. When authoring or repairing
themes/{theme}/**, do not copy resolved values, selectors, or behavior from another theme's VE files or screenshot output. Theme-specific inputs are restricted toscreenshots/{theme}/theme.cssandscreenshots/{theme}/**/style.css. -
Global
--bs-*var values inscope.css.tsmust be sourced fromscreenshots/{theme}/theme.css. The:rootblock in that file is the authoritative source for each theme's resolved CSS custom-property values (e.g.--bs-primary,--bs-border-radius,--bs-link-color, etc.). Never copy Bootstrap's default values for a Bootswatch theme, and never borrow another theme's resolved values. -
CSS custom-property references must be preserved as references, not resolved to static values. If the Bootstrap source CSS writes
var(--bs-border-radius), the VE2 output must writevarBsBorderRadius(the matchingcreateVar()identifier), not the final resolved value (e.g.'0.375rem'). This ensures per-theme values propagate correctly at runtime. -
Font imports for Bootswatch themes must be extracted from
screenshots/{theme}/bootstrap.cssand written tove-project2/src/themes/{theme}/fonts.generated.cssexactly once when creating the theme'sscope.css.ts. Vanilla Extract cannot emit bare@importat-rules, so the generated CSS file preserves the source@importrules and is loaded globally viave-project2/index.html. This step is not repeated when converting individual component families — it belongs solely to the one-time theme scope setup. -
Theme-local selectors and resolved component values must come from
screenshots/{theme}/**/style.css. If a component needs a special-case rule beyond the globaltheme.cssvars, derive it from the matching route-levelstyle.cssfiles for the same theme rather than from another theme or from package sources. -
Source CSS element rules (
h1/h4/p/hr, etc.) must be migrated viacontentscontracts, never by targeting raw elements in selectors. Create a contract class intheme-contract/contents/contract.css.ts, implement theme rules inthemes/{theme}/contents/styles.css.ts, and stamp those classes directly on component elements (for example<h4 class={${theme} ${h4}}>). Do not use selectors like${scope} hror${scope}${component} p. -
Static string class selectors from source CSS (for example
.container,.container-fluid) must not be authored insidethemes/{theme}/{family}/styles.css.ts. Migrate these rules throughtheme-contract/contents/contract.css.tsand implement them inthemes/{theme}/contents/styles.css.ts, then apply the corresponding contents contract classes in markup. Do not write raw selector strings like.containeror.container-fluidin component-family theme files. -
One contract per source class token — never a per-family alias for a shared state class.
.dropdown-item.activeis two tokens and emits${dropdownItem}${active}; the composition happens at the call site. Do not adddropdownItemActive,btnShowHook,navLinkDisabledor anything shaped like them.active,disabled,show,showing,fade,collapsed,collapsingare owned bytheme-contract/literal/contract.css.tsand by nothing else — a second copy in a family module shadows the live one depending on directory read order. Compound selectors already isolate components (${modal}${show}cannot match a dropdown), so a shared hash is safe. A genuine interference case gets a named entry in the divergence manifest, never a family-specific contract. -
Every zero-style contract must be styled by some theme. An unwired contract compiles, exports a real hashed class and renders nothing — the failure is invisible until someone reports that an element "looks unstyled".
npm run check:contract-wiringenforces this before a build andbuild-contract.mjsre-checks it against real hashes; deliberate inertness goes inscripts/contract-wiring-allowlist.mjswith a reason.
Use this checklist for every new component family (e.g. inputs, badges, modals).
For a compact, action-oriented version with gotcha notes see docs/ve2-migration-playbook.md.
Create ve-project2/src/theme-contract/ui/{family}/contract.css.ts:
import { style } from '@vanilla-extract/css'
export const myComponent = style({})
export const myComponentVariant = style({})
// …All exports must be style({}) — no properties.
One export per Bootstrap class token. A rule like .my-component.active does not get a
myComponentActive contract: .active is already owned by theme-contract/literal/contract.css.ts,
and the theme rule composes the two (${myComponent}${active}). See Core Rule 20 — this is the
mistake that left four state contracts exported and unwired for two releases.
Create ve-project2/src/theme-contract/ui/{family}/_vars.css.ts with a createVar() for each Bootstrap CSS custom property used by this family:
import { createVar } from '@vanilla-extract/css'
// Mirror Bootstrap: .my-component { --bs-my-component-padding-x: 1rem; … }
export const varBsMyComponentPaddingX = createVar()
export const varBsMyComponentBorderRadius = createVar()
// …Global --bs-* variables are in theme-contract/_vars.css.ts — import from there, do not re-declare.
For each theme that implements the family, create ve-project2/src/themes/{theme}/ui/{family}/styles.css.ts.
Mirror Bootstrap's CSS literally: declare component vars via vars:, then reference them as property values — exactly as Bootstrap's source CSS does:
import { globalStyle } from '@vanilla-extract/css'
import { myComponent, myComponentVariant } from '../../../../theme-contract/ui/{family}/contract.css'
import { varBsMyComponentPaddingX, varBsMyComponentBorderRadius } from '../../../../theme-contract/ui/{family}/_vars.css'
import { varBsBorderRadius } from '../../../../theme-contract/_vars.css'
import { bootstrapScope } from '../../scope.css'
// SOURCE CSS:
// .my-component {
// --bs-my-component-padding-x: 1rem;
// --bs-my-component-border-radius: var(--bs-border-radius);
// padding: … var(--bs-my-component-padding-x);
// border-radius: var(--bs-my-component-border-radius);
// }
globalStyle(`${bootstrapScope}${myComponent}`, {
vars: {
[varBsMyComponentPaddingX]: '1rem',
[varBsMyComponentBorderRadius]: varBsBorderRadius, // refs inherited global var
},
padding: `… ${varBsMyComponentPaddingX}`,
borderRadius: varBsMyComponentBorderRadius,
})
globalStyle(`${bootstrapScope}${myComponentVariant}`, { /* variant vars + styles */ })Import the styles file as a side-effect import in the component or shell that uses it:
import 'path/to/styles.css'Create component files in ve-project2/src/components/ui/{family}/:
import { useContext } from 'solid-js'
import { ThemeContext } from '../../../../context/ThemeContext'
import { myComponent, myComponentVariant } from '../../../../theme-contract/ui/{family}/contract.css'
const MyComponent = () => {
const theme = useContext(ThemeContext)
return <div class={`${theme} ${myComponent} ${myComponentVariant}`}>…</div>
}Add explicit <Route> entries in ve-project2/src/index.tsx for each leaf component.
In Ve2Shell.tsx (or the relevant shell), add:
import '../../themes/bootstrap/ui/{family}/styles.css'
import '../../themes/sketchy/ui/{family}/styles.css'Because every element carries its own scope class, multiple themes can be nested at any depth without conflicts. Each ThemeContext.Provider overrides the scope for its subtree:
<ThemeContext.Provider value={bootstrapScope}>
<ThemedBody>
<Button /> {/* Bootstrap-styled */}
<ThemeContext.Provider value={sketchyScope}>
<ThemedBody>
<Button /> {/* Sketchy-styled, no conflicts */}
</ThemedBody>
</ThemeContext.Provider>
</ThemedBody>
</ThemeContext.Provider>No @layer, no specificity tricks, no extra selectors needed for any nesting depth.
For patterns that depend on sibling or adjacent-sibling relationships (e.g. Bootstrap's btn-check + adjacent button label), use globalStyle with the scope prefix and both generated class references:
// Disabled checkbox makes the adjacent button label look disabled
globalStyle(`${bootstrapScope}${btnCheck}:disabled + ${bootstrapScope}${btn}`, {
pointerEvents: 'none',
opacity: '0.65',
})Do not use raw class name strings (e.g. '.btn') in selectors. Always reference the generated VE identifiers.
The shipping converter (scripts/generate-ve-literal.mjs; design in docs/ve2-literal-conversion-plan.md) mirrors screenshots/{theme}/bootstrap.css rule‑for‑rule under the element‑owned model with one uniform, deterministic translation — no per‑family heuristics (those were removed in T10):
-
Strict 1:1 token→contract registry. Every Bootstrap class maps to exactly one contract (
.btn→btn,.btn-primary→btnPrimary), and every element tag to one element contract (p→paragraph,button→elButton,h1→h1). Compounds are never synthesized —.btn-primary→${scope}${btnPrimary}, not${scope}${btn}${btnPrimary}— preserving source specificity. Collisions (utility.h1vs elementh1) get acls‑prefixed class contract (clsH1). -
Combinators preserved, scope+contract on each named segment.
.card > .card-header→`${scope}${card} > ${scope}${cardHeader}`;ol ol→`${scope}${elOl} ${scope}${elOl}`. Reboot/element rules therefore only fire when the component stamps the element contract on that tag (enforced by the markup‑parity check). -
*, pseudo‑classes/elements, and attribute selectors pass through verbatim (never mapped to contracts)..table > :not(caption) > * > *→`${scope}${table} > :not(caption) > * > *`. A segment with no class/tag (pure*/pseudo) carries no scope prefix. -
Shared state classes are single global contracts (
show,fade,active,collapsing, …). Compound selectors keep components isolated (${scope}${modal}${show}vs${scope}${dropdownMenu}${show}), so one sharedshowhash is safe. Bootstrap‑JS‑driven components stamp component‑specific hook contracts where the CSS expects them (modalShowHook,dropdownMenuShow,btnShowHook) — every${show}rule must target the contract the JS actually stamps. -
var(--bs-*)stays a contract var reference (varBsBorderRadius), parsed with a realvar()parser (nesting + fallbacks), never resolved to a static value (Core Rule 15). -
Intentional deviations live in the divergence manifest, not in code branches (seed:
body→bodyFrame/bodyTextsplit). Selector‑shape quirks are handled mechanically and are not divergences. -
Strict, no‑fallback. After the Phase‑1 census every token resolves; the emitter runs
--strictand cannot emit a rule‑violating fallback.
Two loaders share one foundation.
scope.css.ts+fonts.generated.css(per‑theme--bs-*values +@importfonts) are generated by the scope‑onlyscripts/generate-ve-theme.mjsand imported by both the literal loader and the still‑livetheme/granularruntime. The granular loader (Ve2GranularShell,useVe2RequiredStyleFamilies) is preserved for the upcoming literal‑based per‑family split milestone.
# Install dependencies (from repo root)
pnpm install
# Build ve-project2
pnpm ve2:build
# Dev server for ve-project2
pnpm ve2:devThe first VE sub-project (ve-project) used a different approach:
- CSS custom properties (
createVar()) for theme tokens - Runtime theme resolver and typed family contracts
- URL-driven theme selection with skip-with-warning for partial coverage
- Scope class carried CSS properties directly (not empty)
That approach is fully documented in:
The element-owned scope model in ve-project2 was chosen because it eliminates the runtime contract complexity while delivering better multi-theme nesting support and a simpler CSS output.