@lineus/svelte-color-scheme
v0.1.2
Published
**_A library for managing light and dark mode for a sveltekit site._**
Readme
@lineus/svelte-color-scheme
A library for managing light and dark mode for a sveltekit site.
Summary
When you create a SchemeState instance ( provided in a svelte context ) that instance uses a svelte MediaQuery, the browser's localStorage, and svelte reactivity to track both the visitor's system scheme preference and their preference on your site to update the current scheme.

Expected Default Behavior
- First time visitors will get their system's current scheme.
- Setting the site state to 'light' or 'dark' will override their system preference.
- When the site state is set to 'system' the site will honor their system setting preference.
- Any change to either the site or system preference will cause the value
of the SchemeState instance's
.currentproperty to update.
Options
- The behavior of defaulting to the system preference can be overriden.
createSchemeState({ default: 'dark' }) and using a custom svelte:head with a fn to
prevent a Flash Of Unwanted Content that updates the classlist or dataset to dark will
mean that your site defaults to dark mode but the user can override it to be light or
follow their system.
- What happens when the SchemeState instance's
.currentproperty is updated is entirely up to you. Put it in an$effector{}and your ui will change accordingly.
Installing
npm
npm install @lineus/svelte-color-scheme
pnpm
pnpm install @lineus/svelte-color-scheme
Provides
createSchemeState()- a fn that creates the context and instantiates SchemeState.getSchemeState()- a fn that retrieves the SchemeState instance from the context.a
<SchemeDatasetHeader />- an optional component to add an iife to<svelte:head>on first load that will set a data attribute called scheme on the html element. This is to prevent a FOUC.a
<SchemeClassHeader />- an optional component to add an iiffe to<svelte:head>on first load that will add a dark class to the html element. This is to prevent a FOUC.
How to use svelte-color-scheme in your sveltekit project
in the script of +layout.svelte (presumably the root level):
- import the createSchemeState function
- call
createSchemeState() - import and add the SchemeDatasetHeader or SchemeClassHeader component or write your own logic to prevent FOUC and include it here. These components are merely provided as a convenience based on two strategies for implementing light/dark mode.
in a scheme selecting component of your own making:
- import the getSchemaState function
- call
const scheme = getSchemeState() - wire up the ui to the state (see examples)
- watch the scheme change in all open tabs :)
How to run the examples
- clone this repo to a folder on your system
- cd into the directory
npm installorpnpm installnpm run dev --openorpnpm run dev --open- interact with the button and the slider to see the scheme change
