use_color_mode
Reactive color mode (dark / light / customs) with auto data persistence.
Demo
Usage
use leptos::prelude::*;
use leptos_use_color_mode::{use_color_mode, UseColorModeReturn};
#[component]
fn Demo() -> impl IntoView {
let UseColorModeReturn {
mode, // Signal<ColorMode::dark | ColorMode::light>
set_mode,
..
} = use_color_mode();
view! { }
}
By default, it will match with users’ browser preference using use_preferred_dark (a.k.a. ColorMode::Auto).
When reading the signal, it will by default return the current color mode (ColorMode::Dark, ColorMode::Light or
your custom modes ColorMode::Custom("some-custom")). The ColorMode::Auto variant can
be included in the returned modes by enabling the emit_auto option and using use_color_mode_with_options.
When writing to the signal (set_mode), it will trigger DOM updates and persist the color mode to local
storage (or your custom storage). You can pass ColorMode::Auto to set back to auto mode.
use leptos::prelude::*;
use leptos_use_color_mode::{ColorMode, use_color_mode, UseColorModeReturn};
#[component]
fn Demo() -> impl IntoView {
let UseColorModeReturn { mode, set_mode, .. } = use_color_mode();
mode.get(); // ColorMode::Dark or ColorMode::Light
set_mode.set(ColorMode::Dark); // change to dark mode and persist
set_mode.set(ColorMode::Auto); // change to auto mode
view! { }
}
Options
use leptos::prelude::*;
use leptos_use_color_mode::{use_color_mode_with_options, UseColorModeOptions, UseColorModeReturn};
#[component]
fn Demo() -> impl IntoView {
let UseColorModeReturn { mode, set_mode, .. } = use_color_mode_with_options(
UseColorModeOptions::default()
.attribute("theme") // instead of writing to `class`
.custom_modes(vec![
// custom colors in addition to light/dark
"dim".to_string(),
"cafe".to_string(),
]),
); // Signal<ColorMode::Dark | ColorMode::Light | ColorMode::Custom("dim") | ColorMode::Custom("cafe")>
view! { }
}
Cookie
To persist color mode in a cookie, use use_cookie_with_options and specify .cookie_enabled(true).
Note: To work with SSR you have to add the
axumoractixfeature as described inuse_cookie.
#![allow(unused)]
fn main() {
use leptos::prelude::*;
use leptos_meta::*;
use leptos_use_color_mode::{use_color_mode_with_options, UseColorModeOptions, UseColorModeReturn};
#[component]
fn Demo() -> impl IntoView {
let UseColorModeReturn { mode, set_mode, .. } = use_color_mode_with_options(
UseColorModeOptions::default()
.cookie_enabled(true),
);
// This adds the color mode class to the `<html>` element even with SSR
view! {
<Html {..} class=move || mode.get().to_string()/>
}
}
}
For a working example please check out the ssr example.
Server-Side Rendering
Make sure you follow the instructions in Server-Side Rendering.
On the server this will try to read the
Sec-CH-Prefers-Color-Scheme header
to determine the color mode. If the header is not present it will return ColorMode::Light.
Please have a look at the linked documentation above for that header to see browser support
as well as potential server requirements.
If you’re using
axumyou have to enable the"axum"feature in your Cargo.toml. In case it’sactix-webenable the feature"actix".
Bring your own header
In case you’re neither using Axum nor Actix or the default implementation is not to your liking,
you can provide your own way of reading the color scheme header value using the option
UseColorModeOptions::ssr_color_header_getter.
Cookie
If cookie_enabled is set to true, a cookie will be used and if present this value will be used
on the server as well as on the client. Please note that you have to add the axum or actix
feature as described in use_cookie.
ColorMode::Auto is stored together with the system’s mode it resolves to (auto-dark or
auto-light), and rewritten when the system switches while a page is open. Without the header
above, the server renders that stored system mode, so only a first visit, or a system that
switched between two visits, shows ColorMode::Light until hydration. A custom mode therefore
can’t start with auto-. The cookie lives for a year by default
(UseColorModeOptions::cookie_max_age).
See also
Installation
cargo add leptos-use-color-mode
Options
UseColorModeOptions
Every option is set with a builder method of the same name, e.g. UseColorModeOptions::default().target(...). See also the API docs.
target
Type: El
Element that the color mode will be applied to. Defaults to the root element of the
document (<html>).
attribute
Type: String
HTML attribute applied to the target element. Defaults to "class".
initial_value
Type: MaybeRwSignal<ColorMode>
Initial value of the color mode. Defaults to "Auto".
initial_value_from_url_param
Type: Option<String>
Discover the initial value of the color mode from an URL parameter. Defaults to None.
initial_value_from_url_param_to_storage
Type: bool
Write the initial value of the discovered color mode from URL parameter to storage.
This only has an effect if initial_value_from_url_param is specified.
Defaults to false.
custom_modes
Type: Vec<String>
Custom modes that you plan to use as ColorMode::Custom(x). Defaults to vec![].
on_changed
Type: OnChangedFn
Custom handler that is called on updates.
If specified this will override the default behavior.
To get the default behaviour back you can call the provided default_handler function.
It takes two parameters:
- mode: ColorMode: The color mode to change to.
-default_handler: Arc<dyn Fn(ColorMode)>: The default handler that would have been called if the on_changed handler had not been specified.
storage_signal
Type: Option<RwSignal<ColorMode>>
When provided, useStorage will be skipped.
Defaults to None.
storage_key
Type: String
Key to persist the data into localStorage/sessionStorage.
Defaults to "leptos-use-color-scheme".
storage
Type: StorageType
Storage type, can be Local or Session or custom.
Defaults to Local.
storage_enabled
Type: bool
If the color mode should be persisted.
Ignored when cookie_enabled is set: the cookie is then the only copy, since the server can
read it and a second one could only disagree with it.
Defaults to true.
cookie_name
Type: String
Name of the cookie that should be used to persist the color mode.
Defaults to "leptos-use-color-scheme".
cookie_enabled
Type: bool
If the color mode should be persisted through a cookie.
Defaults to false.
cookie_max_age
Type: Option<i64>
Max-Age of the cookie in milliseconds. None makes it a session cookie.
Defaults to one year.
emit_auto
Type: bool
Emit auto mode from state
When set to true, preferred mode won’t be translated into light or dark.
This is useful when the fact that auto mode was selected needs to be known.
Defaults to false.
transition_enabled
Type: bool
If transitions on color mode change are enabled. Defaults to false.
listen_to_storage_changes
Type: bool
Listen to changes to this storage key from somewhere else. Defaults to true.
ssr_color_header_getter
Type: Arc<dyn Fn() -> Option<String> + Send + Sync>
Getter function to return the string value of the
Sec-CH-Prefers-Color-Scheme
header.
When you use one of the features "axum" or "actix" there’s a valid default
implementation provided.