Description
The ThemeSwitcher component allows users to switch between different themes (auto, light, dark). It extends the ShadowComponent class and automatically saves the selected theme to local storage, applies it to the document, and synchronizes across browser tabs.
Basic Usage
Use the ThemeSwitcher component to allow users to cycle through themes. Clicking the button cycles through auto → light → dark → auto. The component automatically detects the user's system preference when in auto mode.
<k-theme-switcher></k-theme-switcher>
Custom Padding
You can customize the button padding by setting the --padding CSS custom property. The default padding uses var(--spacer, 1rem).
<k-theme-switcher style="--padding: 0.5rem;"></k-theme-switcher>
<k-theme-switcher style="--padding: 2rem;"></k-theme-switcher>
JavaScript Reference
Constructor
Extends ShadowComponent
new ThemeSwitcher()
Requirements
Properties
currentTheme: string
Gets or sets the current theme. Possible values are "auto", "light", or "dark". This property is reactive and will trigger a re-render when changed. Syncs to current-theme attribute.
CSS Custom Properties
--padding: length
Controls the padding of the theme switcher button. Defaults to var(--spacer, 1rem). You can override this to customize the button's spacing.
k-theme-switcher {
--padding: 0.5rem;
}
Methods
The ThemeSwitcher class does not introduce any new public methods beyond those provided by the ShadowComponent class.
Static Methods
static setTheme(theme): void
Sets the specified theme and saves it to local storage. Also applies the theme to the document element and dispatches a storage event for cross-tab synchronization.
- theme
string- The theme to set. Must be one of:"auto","light", or"dark"
// Programmatically set theme to dark mode
ThemeSwitcher.setTheme('dark');
static getCurrentTheme(): string
Gets the current theme from the document attribute or local storage. Returns "auto" if no theme is set.
// Get the current theme
const currentTheme = ThemeSwitcher.getCurrentTheme();
console.log(currentTheme); // "auto", "light", or "dark"
Automatic Theme Detection
When the theme is set to "auto", the component automatically detects the user's system preference using prefers-color-scheme media query. The detected theme is applied to the document element as an auto-theme attribute.
The component also synchronizes theme changes across browser tabs using the storage event, ensuring a consistent user experience.