Overview
TheThemeToggle component provides a button that toggles between light and dark themes. It features animated sun and moon icons, persists user preference to localStorage, and respects system color scheme preferences.
Props
The ThemeToggle component accepts no props.Features
- Visual Feedback: Animated sun/moon icon transition
- localStorage Persistence: Saves theme preference across sessions
- System Preference Detection: Respects
prefers-color-schememedia query - Custom Element: Uses Web Components for theme management
- Smooth Animations: Sliding indicator with transform transitions
- Accessibility: ARIA attributes for screen readers
Usage
Real-World Example
In Nav Component
Fromsrc/components/Nav.astro:74-76:
How It Works
Theme Detection Priority
- localStorage: If a theme preference is stored, use it
- System Preference: Otherwise, check
prefers-color-scheme: dark - Default: Falls back to light mode
JavaScript Functionality
The component includes a customThemeToggle Web Component:
CSS Class Toggle
When activated, the component adds thetheme-dark class to <html>:
Visual Design
The toggle features a pill-shaped button with two icons:- Sun icon: Represents light mode
- Moon icon: Represents dark mode
Animation
Fromsrc/components/ThemeToggle.astro:36-46:
Integration with Global Theme System
The ThemeToggle works in conjunction with the theme initialization script inMainHead.astro. This ensures:
- Theme is applied immediately on page load (blocking script)
- No flash of wrong theme on navigation
- Theme persists across page refreshes
- System preference is respected on first visit
src/components/MainHead.astro:32-51:
Accessibility
- ARIA Pressed: Button uses
aria-pressedto indicate toggle state - Screen Reader Text:
.sr-onlytext describes the theme - Keyboard Accessible: Full keyboard navigation support
- Visual Feedback: Color changes clearly indicate current state
- Reduced Motion: Respects
prefers-reduced-motionfor animations
Styling with CSS Variables
The component uses these theme variables:--gray-999- Button background--accent-overlay- Border and default icon color--accent-regular- Active indicator background--accent-text-over- Active icon color--theme-transition- Animation duration
The theme toggle requires the Icon component to render the sun and moon icons.