Smoothie 4. Patterns Theme Selector Pattern

Live Demo

Standard Theme Toggle

Features:
• Shows current mode (Light/Dark)
• Click to toggle between modes
• Saves preference to localStorage
• Updates page theme automatically

Icon-Only Variant

Features:
• Compact form (just the icon)
• Perfect for toolbars/headers
• Same toggle functionality
• Same theme broadcast capability

About This Component

<labs-theme-toggle> is an organism-level component that combines theme switching logic with UI presentation. Unlike basic molecules like buttons, it includes:

How It Works

Theme Switching Flow

1. User clicks toggle
The component detects the click and toggles between light/dark
2. State updates
Updates display (icon + label), saves to localStorage
3. Broadcasts change
Sends postMessage to all iframes (if in home view), and emits custom event
4. Page updates
CSS variables update, theme classes applied to document root

Usage Examples

Basic Usage

<labs-theme-toggle></labs-theme-toggle>

Icon-Only Mode

<labs-theme-toggle icon-only></labs-theme-toggle>

JavaScript Event Listener

const toggle = document.querySelector('labs-theme-toggle');
toggle.addEventListener('mode-changed', (e) => {
  console.log('Mode changed to:', e.detail.mode);
});

In a Home View

// In home view, create toggle in header:
<labs-theme-toggle id="main-toggle"></labs-theme-toggle>

// It automatically broadcasts to all iframes:
// window.self === window.top // true in home view

Component Architecture

File Structure

/libs/smoothie-design-system/v3.0/
└── src/components/
└── labs-theme-toggle.js ← Organism component

/smoothie/
└── theme-toggle/ ← Individual page
└── index.html
Why "Organism"?
This component combines multiple concerns: state management, event broadcasting, localStorage handling, and UI rendering. It's too complex for a "molecule" (simple UI component) but too focused for a "template" (page layout). It's the bridge between primitive components and full applications.

Component API

Attributes

  • icon-only — Hide label text, show only emoji icon

Events

// Custom event fired when mode changes
event: 'mode-changed'
detail: { mode: 'light' | 'dark' }

PostMessage (iframe communication)

// Broadcasted to all iframes
{
  type: 'smoothie-theme-update',
  mode: 'light' | 'dark'
}

localStorage

  • smoothie-mode — Persisted current mode (light/dark)