svelte-os-themes
v4.0.2
Published
[](https://svelte-os-themes.vercel.app)
Maintainers
Readme
Svelte OS Themes
Light-weight dark mode helper for Svelte.
Installation
npm install svelte-os-themesUsage
<!-- +layout.svelte -->
<script>
import { ThemeProvider } from 'svelte-os-themes';
let { children } = $props();
</script>
<ThemeProvider
fallback="system"
attribute="class"
storageKey="theme"
colorScheme={true}
system={true}
nonce=""
>
{@render children()}
</ThemeProvider><!-- +page.svelte -->
<script>
import { useTheme } from 'svelte-os-themes';
let theme = useTheme();
$inspect(theme.current);
</script>
<button
type="button"
onclick={() => {
theme.current = 'light';
}}
>
Light
</button>
<button
type="button"
onclick={() => {
theme.current = 'dark';
}}
>
Dark
</button>
<button
type="button"
onclick={() => {
theme.current = 'system';
}}
>
System
</button>API
ThemeProvider
ThemeProvider accepts the following props:
fallbackThe default theme to use when no theme is set in storage.
accepted values:
'light','dark','system'default value:'system'attributeThe attribute to set on the
htmlelement.accepted values:
'class',data-${string}default value:'class'storageKeyThe key to use when storing the theme in
localStorage.accepted values:
<string>default value:'theme'systemWhether to change theme when the OS theme changes.
accepted values:
true,falsedefault value:falsecolorSchemeWhether to add/update the
html'scolor-scheme.accepted values:
true,falsedefault value:truenonceThe nonce to use for the injected script and transition-suppression style.
accepted values:
<string>default value:undefined
useTheme
useTheme does not accept any arguments and returns an object with the following properties.
useTheme must be called in a descendant of ThemeProvider.
currentReturns the current theme when used as a getter and sets the theme when used as a setter.
parseTheme
parseTheme is a helper function that parses any value into a valid theme.
import { parseTheme } from 'svelte-os-themes';
console.log(parseTheme('LIGHT')); // 'light'
console.log(parseTheme('invalid')); // undefined
console.log(parseTheme('invalid', 'dark')); // 'dark'