日本語

Styles switched by a signal

css_when and css_match add a style while an expression over the signals holds. The browser switches it without a request to the server.

A style while an expression is true

El::css_when, fn css_when(self, style: Style, when: impl IntoExpr<S, bool>) -> Self, adds the declarations of style to the element while when is true in the browser. when is a bool signal or any expression over the signals that yields a bool, and it changes without a request to the server. The first HTML already has the style when when is true for the initial signals.

use hypersig::html::li;
use hypersig::style::value::{Color, FontWeight, Opacity, TextDecorationLine, rem};
use hypersig::style::{PseudoClass, Style};
use hypersig::{Page, Signals};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Todo {
    done: bool,
}

let item = li::<Todo>()
    .css(Style::new().padding(rem(0.5)).color(Color::BLACK))
    // While `done` is true: overrides `color: black`.
    .css_when(
        Style::new()
            .color(Color::GRAY)
            .text_decoration_line(TextDecorationLine::LineThrough)
            .on(PseudoClass::Hover, Style::new().opacity(Opacity::Number(0.8))),
        Todo::done(),
    )
    // While `done` is false.
    .css_when(Style::new().font_weight(FontWeight::Number(600.0)), !Todo::done())
    .text("Buy milk");

The style may use conditions of its own, such as the Hover above. Writing .item for the list item, while done is true the browser applies:

.item { padding: 0.5rem; color: black }
.item { color: gray; text-decoration-line: line-through } /* wins over color: black */
.item:hover { opacity: 0.8 }

Which declaration wins

The rules of css_when come after every rule of El::css in the cascade, so while when is true they override the element's own declarations for the same property, including the ones under a condition such as :hover. When when turns false, the element's own declarations apply again.

Two styles switched on at once that set the same property are not checked against each other. The one whose rule comes later in the stylesheet wins, which depends on the conditions and the property, not on the order of the calls. Give two styles that can hold at once different properties, or use css_match below.

One style per value

El::css_match, fn css_match<T: PartialEq + Serialize>(self, value: impl IntoExpr<S, T>, cases: impl IntoIterator<Item = (T, Style)>) -> Self, adds the style of the case whose value equals value. At most one case applies at a time, so two cases never compete for a property. This is the variant half of a recipe: the base goes in El::css, and each case adds what one value changes.

use hypersig::html::span;
use hypersig::style::value::{Color, rem};
use hypersig::style::Style;
use hypersig::{Page, Signals};
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Clone, Copy, PartialEq)]
enum Status {
    Draft,
    Review,
    Published,
}

#[derive(Signals, Serialize, Deserialize)]
struct Post {
    status: Status,
}

let badge = span::<Post>()
    .css(Style::new().padding(rem(0.25)).color(Color::WHITE))
    // One case applies at a time, so the cases never compete for `background-color`.
    .css_match(
        Post::status(),
        [
            (Status::Draft, Style::new().background_color(Color::GRAY)),
            (Status::Review, Style::new().background_color(Color::ORANGE)),
            // Leaving out `Published` compiles, and the badge then has no background.
            (Status::Published, Style::new().background_color(Color::GREEN)),
        ],
    )
    .text("Status");

The badge below takes its color from css_match over an enum:

Result

status.rs
use hypersig::html::{div, span};
use hypersig::style::pattern::{hstack, stack};
use hypersig::style::value::{Color, FontWeight, px, rem};
use hypersig::style::{Media, Style, Theme, Token};
use hypersig::{Page, Signals, if_else};
use hypersig_ui::{ButtonSize, ButtonVariant, button};
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Clone, Copy, PartialEq)]
pub(super) enum Status {
    Idle,
    Busy,
    Done,
}

#[derive(Signals, Serialize, Deserialize)]
pub(super) struct Build {
    status: Status,
}

pub(super) fn page() -> Page<Build> {
    let status = Build::status();
    let done = Token::new("done", Color::hex(0x0015_803d));
    let badge = span()
        .css(
            Style::new()
                .padding_block(rem(0.125))
                .padding_inline(rem(0.625))
                .border_radius(px(999))
                .font_size(rem(0.75))
                .font_weight(FontWeight::Number(600.0))
                .color(Color::WHITE),
        )
        .css_match(
            status,
            [
                (
                    Status::Idle,
                    Style::new().background_color(Color::hex(0x0052_525b)),
                ),
                (
                    Status::Busy,
                    Style::new().background_color(Color::hex(0x00b4_5309)),
                ),
                (Status::Done, Style::new().background_color(done.var())),
            ],
        )
        .bind_text(if_else(
            status.equals(&Status::Idle),
            "Idle",
            if_else(
                status.equals(&Status::Busy),
                "Building",
                "Done",
            ),
        ));
    let set = |value: Status, label: &str| {
        button(ButtonVariant::Outline, ButtonSize::Sm)
            .on_click(status.set(&value))
            .text(label)
    };
    Page::new(
        "Build",
        Build {
            status: Status::Idle,
        },
    )
    .theme(Theme::new().on(
        Media::Dark,
        Theme::new().set(&done, Color::hex(0x0016_a34a)),
    ))
    .child(
        div().css(stack(rem(1))).child(badge).child(
            div()
                .css(hstack(rem(0.5)))
                .child(set(
                    Status::Idle,
                    "Idle",
                ))
                .child(set(
                    Status::Busy,
                    "Busy",
                ))
                .child(set(
                    Status::Done,
                    "Done",
                )),
        ),
    )
}

When the server knows the value

Nothing checks that the cases of css_match cover every value of T. A value with no case adds nothing. Where the value is known on the server and does not change in the browser, call a function that returns a Style from a match instead, which the compiler checks for every variant:

use hypersig::html::{El, span};
use hypersig::style::Style;
use hypersig::style::value::Color;
use hypersig::Signals;
use serde::{Deserialize, Serialize};

#[derive(Clone, Copy)]
enum Status {
    Draft,
    Review,
    Published,
}

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

// Adding a variant to `Status` is a compile error here until it has a style.
fn status_style(status: Status) -> Style {
    match status {
        Status::Draft => Style::new().background_color(Color::GRAY),
        Status::Review => Style::new().background_color(Color::ORANGE),
        Status::Published => Style::new().background_color(Color::GREEN),
    }
}

fn badge(status: Status) -> El<Posts> {
    span().css(status_style(status)).text("Status")
}

The condition is an expression of type bool

when must be an expression of type bool on the page's signals. A signal of another type is a compile error, so compare it to a value first, as with Todo::title().is_empty():

use hypersig::html::li;
use hypersig::style::Style;
use hypersig::style::value::Color;
use hypersig::Signals;
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Todo {
    title: String,
}

// error[E0277]: `Sig<Todo, String>` is not an expression of type `bool` on the page whose signals are `Todo`
let item = li::<Todo>().css_when(Style::new().color(Color::GRAY), Todo::title());

On the whole page

Page::css_when and Page::css_match do the same on <body>. Tokens set this way reach every element of the page and the background of <body> itself, which a style on an element inside it cannot reach. Dark mode uses them for a color scheme picker.

What the types leave unchecked

  • Two styles of css_when that hold at once and set the same property are not checked against each other, as above.
  • The cases of css_match are not checked for covering every value of T, and a value with no case adds nothing.
  • For a value that no fixed set holds, such as a width in percent, El::bind_style and El::bind_token set a property from a string, which is not checked. Tokens and Unchecked values cover them.

Next

Tokens names a value that several styles read, so one change of a signal can restyle many elements.