ModeWatcher
API Reference for the ModeWatcher component.
Usage
Add the ModeWatcher component to your root +layout.svelte file to automatically apply mode and theme preferences:
<script lang="ts">
import { ModeWatcher } from "mode-watcher";
let { children } = $props();
</script>
<ModeWatcher />
{@render children()}
ModeWatcher will:
- Detect user mode preferences (
light,dark, orsystem) - Apply the appropriate class (dark by default) to the
<html>element - Set the
color-schemeattribute accordingly - Optionally apply a theme via the
data-themeattribute
Features
Disable Tracking
ModeWatcher will automatically track operating system preferences and apply these if no user preference is set. If you wish to disable this behavior, set the track prop to false:
<ModeWatcher track={false} />
Default Mode
Use the defaultMode prop to specify a fallback when no user preference is available:
<ModeWatcher defaultMode="dark" />
Themes
In addition to the dark, light, and system modes, ModeWatcher can also be configured with a theme which will be applied to the root html element like so:
<html data-theme="your-custom-theme"></html>
Theme Colors
Manage the browser's <meta name="theme-color"> dynamically based on mode:
<ModeWatcher themeColors={{ dark: "#000", light: "#fff" }} />
Custom Class Names
Customize the class names added to <html> when switching modes:
<ModeWatcher darkClassNames={["dddd"]} lightClassNames={["fff"]} />
Now, when the mode is dark, the root html element will have the dddd class, and when the mode is light, the root html element will have the fff class.
Custom Local Storage Keys
Override the default localStorage keys:
<ModeWatcher modeStorageKey="my-mode-key" themeStorageKey="my-theme-key" />
CSP Nonce Support
Provide a nonce if using a strict Content Security Policy.
This will be applied to the injected <script> tag used for pre-hydration mode setting:
<ModeWatcher nonce="my-secure-nonce" />
Disable Script Injection
Prevent ModeWatcher from injecting the initial head script by setting:
<ModeWatcher disableHeadScriptInjection={true} />
Props
The ModeWatcher component accepts the following props:
The default theme to use, which will be applied to the root html element and can be managed with the setTheme function.
The classes to add to the root html element when the mode is 'dark'.
The classes to add to the root html element when the mode is 'light'.
Whether to run the mode changes synchronously instead of using an animation frame. If true, will have an impact on blocking performance due to blocking the main thread.
Only applicable if disableTransitions is set to true.