| title | ModeWatcher |
|---|---|
| description | API Reference for the ModeWatcher component. |
| section | Components |
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
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} />Use the defaultMode prop to specify a fallback when no user preference is available:
<ModeWatcher defaultMode="dark" />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>Manage the browser's <meta name="theme-color"> dynamically based on mode:
<ModeWatcher themeColors={{ dark: "#000", light: "#fff" }} />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.
Override the default localStorage keys:
<ModeWatcher modeStorageKey="my-mode-key" themeStorageKey="my-theme-key" />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" />Prevent ModeWatcher from injecting the initial head script by setting:
<ModeWatcher disableHeadScriptInjection={true} />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.