Skip to content

Latest commit

 

History

History
465 lines (346 loc) · 24.4 KB

ve-architecture.md

File metadata and controls

465 lines (346 loc) · 24.4 KB

Vanilla Extract Architecture (Element-Owned Scope)

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:


Core Philosophy

The element-owned scope model removes two problems that plagued ve-project (v1):

  1. No global element styling. Nothing styles bare elements (body, h1, button, etc.) globally. Every visual rule is opt-in, applied through explicit class composition.
  2. 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.


Concepts

Scope class

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: ... }).

Contract class

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, color

Again, no CSS properties embedded — only stable hashed class names.

Theme rules

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',
})

ThemeContext

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'

Element stamping (components)

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.

ThemedBody

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.

Ve2 shell runtime

ve-project2 now uses a runtime wrapper shell that keeps the legacy full-theme mode as default, while supporting opt-in granular family loading.

  • Ve2ShellRuntime chooses mode from URL query:
    • default mode: full-theme Ve2Shell
    • granular mode: ?style-loader=granular (or ?styleLoader=granular) uses Ve2GranularShell
  • Ve2GranularShell still provides the same ThemeContext scope class, but loads style families on demand via dynamic imports and dedupe caches.
  • If a route is not mapped to known granular families, Ve2GranularShell falls 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>
)

Component-to-shell family requests

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)

File Structure

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

Core Rules

  1. Scope and contract classes must be empty style({}) — no CSS properties embedded.
  2. All styling goes through globalStyle(scope + contract, props) — compound selector with no space.
  3. No global element selectors (body, button, h1, etc.).
  4. Use createVar() and vars: to mirror Bootstrap's CSS custom-property structure. Component-level vars (--bs-badge-padding-x, etc.) live in theme-contract/ui/{family}/_vars.css.ts. Global vars (--bs-border-radius, --bs-primary, etc.) live in theme-contract/_vars.css.ts and are assigned on ${scope}${vars} so all descendants inherit them via CSS cascade.
  5. Every styled element carries both the scope class and its contract class(es).
  6. Root theme vars and body/text styles use dedicated root contracts: vars hosts global --bs-*, while body/bodyText define layout and typography.
  7. Only these static class names are allowed in component markup: bd-example-ve2, pwhook-* screenshot hooks. All other styling comes from VE imports.
  8. ThemeContext provides the active scope class string. Components read it via useContext(ThemeContext) — no prop-drilling.
  9. Leaf components should declare family requirements with ve2RequiredStyleFamilies and call useVe2RequiredStyleFamilies(...). Under full-theme shell this is a safe no-op; under granular shell it drives on-demand family loading.
  10. Ve2ShellRuntime is the entry shell. Default behavior remains full-theme loading; granular mode is opt-in through query param.
  11. 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.
  12. ThemedBody (or equivalent) must wrap any region that requires body-level theme styles (font, color, background).
  13. 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 to screenshots/{theme}/theme.css and screenshots/{theme}/**/style.css.
  14. Global --bs-* var values in scope.css.ts must be sourced from screenshots/{theme}/theme.css. The :root block 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.
  15. 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 write varBsBorderRadius (the matching createVar() identifier), not the final resolved value (e.g. '0.375rem'). This ensures per-theme values propagate correctly at runtime.
  16. Font imports for Bootswatch themes must be extracted from screenshots/{theme}/bootstrap.css and written to ve-project2/src/themes/{theme}/fonts.generated.css exactly once when creating the theme's scope.css.ts. Vanilla Extract cannot emit bare @import at-rules, so the generated CSS file preserves the source @import rules and is loaded globally via ve-project2/index.html. This step is not repeated when converting individual component families — it belongs solely to the one-time theme scope setup.
  17. Theme-local selectors and resolved component values must come from screenshots/{theme}/**/style.css. If a component needs a special-case rule beyond the global theme.css vars, derive it from the matching route-level style.css files for the same theme rather than from another theme or from package sources.
  18. Source CSS element rules (h1/h4/p/hr, etc.) must be migrated via contents contracts, never by targeting raw elements in selectors. Create a contract class in theme-contract/contents/contract.css.ts, implement theme rules in themes/{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} hr or ${scope}${component} p.
  19. Static string class selectors from source CSS (for example .container, .container-fluid) must not be authored inside themes/{theme}/{family}/styles.css.ts. Migrate these rules through theme-contract/contents/contract.css.ts and implement them in themes/{theme}/contents/styles.css.ts, then apply the corresponding contents contract classes in markup. Do not write raw selector strings like .container or .container-fluid in component-family theme files.
  20. One contract per source class token — never a per-family alias for a shared state class. .dropdown-item.active is two tokens and emits ${dropdownItem}${active}; the composition happens at the call site. Do not add dropdownItemActive, btnShowHook, navLinkDisabled or anything shaped like them. active, disabled, show, showing, fade, collapsed, collapsing are owned by theme-contract/literal/contract.css.ts and 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.
  21. 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-wiring enforces this before a build and build-contract.mjs re-checks it against real hashes; deliberate inertness goes in scripts/contract-wiring-allowlist.mjs with a reason.

Adding a New Bootstrap Component Family

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.

1. Define contract classes and component vars

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.

2. Implement theme rules

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'

3. Create components

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>
}

4. Wire routes

Add explicit <Route> entries in ve-project2/src/index.tsx for each leaf component.

5. Add theme side-effect import

In Ve2Shell.tsx (or the relevant shell), add:

import '../../themes/bootstrap/ui/{family}/styles.css'
import '../../themes/sketchy/ui/{family}/styles.css'

Multi-Theme Nesting

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.


Cross-Class Selector Rule

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.


Literal converter selector model (v2)

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):

  1. 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 .h1 vs element h1) get a cls‑prefixed class contract (clsH1).
  2. 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).
  3. *, 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.
  4. 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 shared show hash 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.
  5. var(--bs-*) stays a contract var reference (varBsBorderRadius), parsed with a real var() parser (nesting + fallbacks), never resolved to a static value (Core Rule 15).
  6. Intentional deviations live in the divergence manifest, not in code branches (seed: body → bodyFrame/bodyText split). Selector‑shape quirks are handled mechanically and are not divergences.
  7. Strict, no‑fallback. After the Phase‑1 census every token resolves; the emitter runs --strict and cannot emit a rule‑violating fallback.

Two loaders share one foundation. scope.css.ts + fonts.generated.css (per‑theme --bs-* values + @import fonts) are generated by the scope‑only scripts/generate-ve-theme.mjs and imported by both the literal loader and the still‑live theme/granular runtime. The granular loader (Ve2GranularShell, useVe2RequiredStyleFamilies) is preserved for the upcoming literal‑based per‑family split milestone.


Development and Build

# Install dependencies (from repo root)
pnpm install

# Build ve-project2
pnpm ve2:build

# Dev server for ve-project2
pnpm ve2:dev

Historical Context

The 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.