Your Design System Is Just a Component Library — Unless You Add These Three Layers
This article explains why most design systems are merely component libraries, detailing a three-layer token architecture, CSS @layer priority management, component contract standards, Web Component pitfalls, theme switching implementation, and versioning strategies to build a true constraint-based system that scales across hundreds of pages.
Three Layers and Their Failure Modes
A design system consists of tokens (values), components (behavior), and specifications (usage). Missing any layer causes regression into a code repository waiting to be copied.
Token layer : colors, spacing, type scale, radii, shadows, motion durations. Typical failure: only raw values exist; theme changes require global find-and-replace.
Component layer : interaction, states, accessibility. Typical failure: only default state built; loading, disabled, keyboard states missing.
Specification layer : when to use which component, dos and don'ts. Typical failure: only Storybook exists; no guidance on when not to use.
Component Layer's Real Cost Is the State Matrix
A button must cover:
type: primary / secondary / ghost / danger
state: default / hover / active / focus-visible / disabled / loading
size: sm / md / lg
4 × 6 × 3 = 72 combinationsWithout tokens, that's 72 hard-coded colors; with tokens, it's 6 semantic variables × 3 size variables.
Tokens: Must Be Three Layers, Not One
/* ① Raw layer: only describes "what color", not where used */
:root {
--blue-500: #2f6fed;
--blue-600: #2459c4;
--gray-50: #f7f8fa;
--gray-900: #1a1d21;
--space-2: 8px;
--space-4: 16px;
--radius-md: 8px;
}
/* ② Semantic layer: describes "where used"; theme switch only changes this layer */
:root {
--color-primary: var(--blue-500);
--color-primary-hover: var(--blue-600);
--color-bg: var(--gray-50);
--color-text: var(--gray-900);
--color-border: #e3e6ea;
}
html[data-theme='dark'] {
--color-primary: #6f9bff;
--color-bg: #14161a;
--color-text: #e8eaed;
--color-border: #2a2e35;
}
/* ③ Component layer: used only inside components, can override semantic layer */
.btn {
--btn-bg: var(--color-primary);
--btn-bg-hover: var(--color-primary-hover);
--btn-padding: var(--space-2) var(--space-4);
}Single rule: Application code and component styles may only reference semantic or component layer, never raw layer.
/* ❌ Dark theme will miss this */
.page-header { background: var(--gray-50); }
/* ✅ Theme switches automatically */
.page-header { background: var(--color-bg); }Enforce via CI: grep component directory for var(--blue- or var(--gray- and fail the build. One check beats ten pages of docs.
Naming: Don't Invent Your Own System
Suffixes like -subtle, -strong, -elevated, -muted are industry consensus. Custom names like --color-bg-2 or --color-bg-light2 cost you: newcomers can't guess, AI can't guess.
Flatten Priority with @layer
Design systems fear consumers writing !important. @layer declares layer order; later layers win regardless of selector specificity:
/* Order = priority: later wins */
@layer reset, tokens, components, utilities, overrides;
@layer components {
.btn { padding: var(--btn-padding); background: var(--btn-bg); }
}
@layer utilities {
.u-hidden { display: none !important; } /* only utilities may use !important */
}
/* Consumer overrides need no higher specificity, no !important */
@layer overrides {
.order-page .btn { background: #e0533d; }
}Result: .order-page .btn (specificity 0,2,0) overrides .btn.btn-primary:not(:disabled) (0,4,1) because it lives in a later layer. This solves the toughest UI library integration problem — consumers used to modify source or stack !important; now they just drop rules into the overrides layer.
Caveat: browsers without @layer support drop the entire block, so layer styles must not be critical "fail-if-missing" styles.
Component Contracts: More Important Than Styles
1. Fixed Prop Naming
Size : size="sm|md|lg" (anti-patterns: small, large, size="1")
Variant : variant="primary|ghost" (anti-patterns: type, kind, theme mixed)
State : disabled, loading, readonly (anti-patterns: isDisable, loadingState)
Boolean : no value = true (anti-pattern: disabled="false" treated as truthy string)
Hard trap: HTML attributes are strings; disabled="false" in native semantics still disables the element.
2. Events Must Pierce Shadow DOM
this.dispatchEvent(new CustomEvent('value-change', {
detail: { value },
bubbles: true, // allows host to use event delegation
composed: true // critical: pierces Shadow DOM boundary
}))Missing composed: true is the most common "event not firing" cause — Shadow DOM boundary intercepts it, Vue listeners never receive it.
3. Accessibility Baseline
Keyboard reachable & operable: custom elements default non-focusable; need tabindex="0" + keyboard handlers, or just use native semantic elements.
Visible focus: :focus-visible must have explicit outline; don't just do outline: none .
State announced to screen readers: aria-disabled (not just a class), aria-busy (loading), aria-expanded (collapse).
Contrast ≥ 4.5:1: pick compliant colors at token layer; don't expect consumers to adjust.
Why Web Components as Foundation
Core reason: style isolation + cross-framework .
class DsButton extends HTMLElement {
static get observedAttributes() { return ['variant', 'size', 'disabled'] }
constructor() {
super()
this.attachShadow({ mode: 'open' }) // styles naturally don't leak out, don't get polluted
}
connectedCallback() { this.render() }
attributeChangedCallback() { if (this.isConnected) this.render() }
render() {
this.shadowRoot.innerHTML = `
<style>
:host { display: inline-flex; font: inherit; }
:host([disabled]) { opacity: .5; pointer-events: none; }
button {
all: unset; /* wipe host page button styles */
padding: var(--ds-btn-padding, 8px 16px);
background: var(--ds-btn-bg, var(--color-primary));
}
</style>
<button part="button" aria-busy="${this.hasAttribute('loading')}">
<slot></slot>
</button>
`
}
}
customElements.define('ds-button', DsButton)mode: 'open'is mandatory — closed makes debugging, testing, and part customization harder while adding negligible isolation.
Three Must-Know Pitfalls
① Forms don't recognize it : custom elements don't participate in <form> submission by default. To participate, use ElementInternals:
class DsInput extends HTMLElement {
static formAssociated = true // key switch
constructor() {
super()
this._internals = this.attachInternals()
this.attachShadow({ mode: 'open' })
}
set value(v) { this._internals.setFormValue(v) } // now submits with form
}② SSR flashes : customElements.define doesn't exist on server; first paint shows "unupgraded element". Provide a placeholder:
ds-button:not(:defined) { display: inline-block; min-height: 32px; }③ Fonts don't inherit : font-family inside Shadow DOM doesn't auto-inherit from host. Missing :host { font: inherit } manifests as "component font suddenly changed", and it's hard to trace to isolation.
Theme Switching: Three Things Beyond Tokens
export function applyTheme(mode) {
const resolved = mode === 'system'
? (matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')
: mode
document.documentElement.dataset.theme = resolved
localStorage.setItem('app-theme', mode) // store original choice, not resolved result
}Three easy misses:
Store user choice, not resolved result : if user picks "follow system", store system; otherwise system change won't reflect on page.
First-paint flash : inline a synchronous script in <head> to set data-theme before framework mounts.
color-scheme : html { color-scheme: light dark } makes scrollbars, form controls, default backgrounds follow; only changing CSS variables yields "white background with black scrollbar".
<script>
// Must be inline and synchronous to avoid dark user seeing white flash
const m = localStorage.getItem('app-theme') || 'system'
const dark = m === 'dark' || (m === 'system' && matchMedia('(prefers-color-scheme: dark)').matches)
document.documentElement.dataset.theme = dark ? 'dark' : 'light'
</script>Version Strategy: Renames Must Keep Aliases
Token addition (e.g., new --color-success) → patch
Component prop addition (e.g., size="xl") → minor
Token rename/delete (e.g., --color-bg → --surface) → major + keep alias layer for transition
Component default change (e.g., default md → sm) → minor, but mark in changelog
:root {
--surface: var(--gray-50);
--color-bg: var(--surface); /* old name kept two major versions, migrate gradually */
}Renaming without aliases = all consumers break on the same day.
Documentation site minimum isn't prettiness; it's searchable + has counter-examples : every component page needs "when not to use", token pages show color swatches and variable names — generate from CSS via script, don't hand-copy ; hand-copied token tables inevitably drift from code.
Zero-to-Production Sequence
1. Tokens only (color/spacing/type/radii) + dark mapping ← fastest ROI, lowest risk
2. Wire 3 real pages, replace hard-coded colors with semantic tokens
3. CI check: "no raw token references" ← prevent regression
4. Extract 5 highest-frequency components (button/input/table/modal/tabs), complete state matrices
5. Component styles into @layer components, utilities into utilities
6. Build doc site, auto-generate token tables
7. Then consider cross-framework: rewrite most stable components as Web ComponentsStep 7 last isn't conservative. Web Component isolation blocks the "consumer secretly tweaks styles" shortcut; before tokens and contracts stabilize, it only becomes friction.
Quick Reference
Theme switch without component changes : three-layer tokens; consumers only reference semantic layer
Component-local overrides : component-layer variables --btn-bg: var(--color-primary) Prevent consumer !important : @layer reset, tokens, components, utilities, overrides Prevent direct raw color usage : CI grep component dir; error on var(--blue- Unified component props : size / variant / disabled / loading four-piece set
Events received by Vue : CustomEvent with composed: true Custom element in form : static formAssociated = true + setFormValue() Shadow DOM font mismatch : :host { font: inherit } Dark mode first-paint no flash : <head> inline script sets data-theme early, plus color-scheme Token rename without breakage : keep alias for two major versions
Docs never drift : token tables generated from CSS scan, not hand-copied
Bottom line: A design system isn't "a set of components"; it's "a set of constraints" — more constraints mean more consistency across pages and cheaper changes.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
