日本語

Dark mode

Dark mode is a second set of values for the same tokens, applied while the system prefers dark or while a signal holds the visitor's choice.

Colors as tokens

Read every color that changes with the scheme from a token, and give each token its light value as the default. Dark mode is then a second set of values for the same tokens, and no element's style has to change.

Following the system

Theme::on(Media::Dark, ..) sets the dark values while the system prefers a dark color scheme. The color-scheme property tells the browser to draw its own parts, such as scrollbars and form controls, in the same scheme:

use hypersig::html::p;
use hypersig::style::value::{Color, ColorScheme};
use hypersig::style::{Element, Global, Media, Selector, Style, Theme, Token};
use hypersig::{Page, Signals};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Blog {}

// The defaults are the light values.
let background = Token::new("background", Color::WHITE);
let foreground = Token::new("foreground", Color::hex(0x0009_090b));

let html = Page::new("Blog", Blog {})
    .theme(Theme::new().on(
        Media::Dark,
        Theme::new()
            .set(&background, Color::hex(0x0009_090b))
            .set(&foreground, Color::hex(0x00fa_fafa)),
    ))
    .global(
        Global::new()
            // Scrollbars and form controls follow the system too.
            .rule(Selector::Root, Style::new().color_scheme(ColorScheme::LightDark))
            .rule(
                Element::Body,
                Style::new().background_color(background.var()).color(foreground.var()),
            ),
    )
    .child(p().text("Hello"))
    .render();
:root { color-scheme: light dark }
body { background-color: var(--background, white); color: var(--foreground, #09090b) }
@media (prefers-color-scheme: dark) { :root { --background: #09090b; --foreground: #fafafa } }

ColorScheme has LightDark for light dark, which follows the system, and Light and Dark for a page that is always one of them. A value such as only dark goes through raw, which Unchecked values covers.

Letting the visitor pick

A picker keeps the choice in a signal and sets the tokens on <body> with Page::css_match, so they reach every element and the background of <body> itself. Page::persist keeps the signal in localStorage, so the next page load starts from the stored choice:

use hypersig::html::{button, div};
use hypersig::style::value::{Color, ColorScheme};
use hypersig::style::{Element, Global, Media, Style, Theme, Token};
use hypersig::{Page, Signals};
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Clone, Copy, PartialEq)]
enum Scheme {
    System,
    Light,
    Dark,
}

#[derive(Signals, Serialize, Deserialize)]
struct App {
    scheme: Scheme,
}

let background = Token::new("background", Color::WHITE);
let foreground = Token::new("foreground", Color::hex(0x0009_090b));
let light = Style::new()
    .token(&background, Color::WHITE)
    .token(&foreground, Color::hex(0x0009_090b))
    .color_scheme(ColorScheme::Light);
let dark = Style::new()
    .token(&background, Color::hex(0x0009_090b))
    .token(&foreground, Color::hex(0x00fa_fafa))
    .color_scheme(ColorScheme::Dark);

let scheme = App::scheme();
let html = Page::new("App", App { scheme: Scheme::System })
    // `Scheme::System`, which has no case below, follows the system.
    .theme(Theme::new().on(Media::Dark, Theme::new()
        .set(&background, Color::hex(0x0009_090b))
        .set(&foreground, Color::hex(0x00fa_fafa))))
    .global(Global::new().rule(
        Element::Body,
        Style::new().background_color(background.var()).color(foreground.var()),
    ))
    // On `<body>`, so the tokens reach its own background.
    .css_match(scheme, [(Scheme::Light, light), (Scheme::Dark, dark)])
    // The next page load starts from the stored choice.
    .persist(scheme)
    .child(
        div()
            .child(button().on_click(scheme.set(&Scheme::System)).text("System"))
            .child(button().on_click(scheme.set(&Scheme::Light)).text("Light"))
            .child(button().on_click(scheme.set(&Scheme::Dark)).text("Dark")),
    )
    .render();

Each value of Scheme gives this result:

  • System has no case, so <body> gets no tokens and the theme on :root applies: light, or dark while the system prefers dark.
  • Dark sets the dark values on <body>, which win over the values on :root for everything inside <body>.
  • Light sets the light values on <body>. It needs a case of its own, because the theme sets the dark values on :root while the system prefers dark.

hypersig_ui has these styles ready as hypersig_ui::dark() and hypersig_ui::light(). The preview below puts them on a <div> with El::css_match, so only the preview changes:

Result

theme.rs
use hypersig::html::div;
use hypersig::style::Style;
use hypersig::style::pattern::stack;
use hypersig::style::value::rem;
use hypersig::{Page, Signals};
use hypersig_ui::{
    ButtonSize, ButtonVariant, Level, button, card, card_content, card_description, card_header,
    card_title, select_field, switch, token,
};
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Clone, Copy, PartialEq)]
pub(super) enum Scheme {
    System,
    Light,
    Dark,
}

#[derive(Signals, Serialize, Deserialize)]
pub(super) struct Preview {
    scheme: Scheme,
    on: bool,
}

pub(super) fn page() -> Page<Preview> {
    let initial = Preview {
        scheme: Scheme::System,
        on: true,
    };
    Page::new(
        "Preview",
        initial,
    )
    .child(
        div()
            .css(
                stack(rem(1))
                    .padding(rem(1))
                    .background_color(token::background().var())
                    .color(token::foreground().var()),
            )
            .css_match(
                Preview::scheme(),
                [
                    (Scheme::Light, hypersig_ui::light()),
                    (Scheme::Dark, hypersig_ui::dark()),
                ],
            )
            .child(
                div()
                    .css(Style::new().max_width(rem(12)))
                    .child(select_field(
                        "Theme",
                        Preview::scheme(),
                        [
                            (
                                Scheme::System,
                                "System",
                            ),
                            (
                                Scheme::Light,
                                "Light",
                            ),
                            (
                                Scheme::Dark,
                                "Dark",
                            ),
                        ],
                    )),
            )
            .child(
                card()
                    .child(
                        card_header()
                            .child(card_title(Level::H2).text("Notifications"))
                            .child(card_description().text("Choose what reaches your inbox.")),
                    )
                    .child(
                        card_content()
                            .css(stack(rem(1)))
                            .child(switch(
                                "Product updates",
                                Preview::on(),
                            ))
                            .child(div().child(
                                button(ButtonVariant::Default, ButtonSize::Sm).text("Save"),
                            )),
                    ),
            ),
    )
}

What the types leave unchecked

  • Style::on(Media::Dark, ..) on an element follows the system, not the picker. A color that should follow the picker is read from a token.
  • Nothing checks that the dark values cover every token the light ones do. A token left out keeps its light value in dark mode.
  • The page's own scrollbar follows color-scheme on <html>, not on <body>. With light dark on :root, it keeps the system's scheme while <body> shows the picked one.
  • The server renders the first HTML from the initial value of the signal, because it never sees the stored one. Where they differ, the page stays hidden until the stored scheme is drawn, as Signals kept across page loads explains.

Next

Rules by tag styles <body> and the other elements of the page by their tag. Theming shows the theme button of this site's header, which animates the change with a view transition.