English

シグナルで切り替えるスタイル

css_when と css_match は、シグナルから作る式が成り立つ間だけスタイルを追加します。切り替えはブラウザが行い、サーバーへのリクエストは発生しません。

式が真の間だけのスタイル

El::css_when(fn css_when(self, style: Style, when: impl IntoExpr<S, bool>) -> Self)は、ブラウザで when が真の間、style の宣言を要素に追加します。when は bool のシグナルか、シグナルから bool を作る任意の式で、サーバーへのリクエストなしに切り替わります。初期のシグナルで when が真なら、最初の HTML からそのスタイルが付いています。

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");

スタイルは上の Hover のように自分の条件を使えます。リスト項目を .item と書くと、done が真の間にブラウザが適用するのは次の CSS です。

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

どの宣言が優先されるか

css_when のルールはカスケードの中で El::css のどのルールよりもあとに来ます。そのため when が真の間は、:hover のような条件の下にあるものも含めて、同じプロパティについて要素自身の宣言を上書きします。when が偽になると、要素自身の宣言がまた適用されます。

同時に有効になった 2 つのスタイルが同じプロパティを設定しても、互いに検査はしません。優先されるのはスタイルシートであとに来るルールで、それは条件とプロパティで決まり、呼び出しの順には左右されません。同時に有効になりうる 2 つのスタイルには別々のプロパティを設定するか、下の css_match を使ってください。

値ごとに 1 つのスタイル

El::css_match(fn css_match<T: PartialEq + Serialize>(self, value: impl IntoExpr<S, T>, cases: impl IntoIterator<Item = (T, Style)>) -> Self)は、値が value と等しいケースのスタイルを追加します。一度に適用されるケースは 1 つまでなので、2 つのケースが同じプロパティを取り合うことはありません。レシピでいえばバリアントの部分にあたります。基本のスタイルは El::css に書き、ケースごとに、その値で変わる部分だけを追加します。

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");

下のバッジは、列挙型に対する css_match で色が決まります。

実行結果

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),
            "待機中",
            if_else(
                status.equals(&Status::Busy),
                "ビルド中",
                "完了",
            ),
        ));
    let set = |value: Status, label: &str| {
        button(ButtonVariant::Outline, ButtonSize::Sm)
            .on_click(status.set(&value))
            .text(label)
    };
    Page::new(
        "ビルド",
        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,
                    "待機中",
                ))
                .child(set(
                    Status::Busy,
                    "ビルド中",
                ))
                .child(set(
                    Status::Done,
                    "完了",
                )),
        ),
    )
}

値がサーバーで決まる場合

css_match のケースが T のすべての値を網羅しているかどうかは検査しません。どのケースにも当たらない値は何も追加しません。値がサーバーで決まり、ブラウザで変わらない場合は、代わりに match で Style を返す関数を呼びます。そうすれば、すべてのバリアントをコンパイラが検査します。

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")
}

条件は bool の式

when はページのシグナルから作る bool の式でなければなりません。ほかの型のシグナルを渡すとコンパイルエラーになるので、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());

ページ全体に付ける

Page::css_when と Page::css_match は、同じことを <body> に対して行います。こうして設定したトークンは、ページのすべての要素と <body> 自身の背景に届きます。<body> の内側の要素に付けたスタイルでは、<body> の背景には届きません。ダークモードではこれを配色の切り替えに使います。

型では検査しないこと

  • 上で説明したとおり、同時に有効になった css_when の 2 つのスタイルが同じプロパティを設定しても、互いに検査はしません。
  • css_match のケースが T のすべての値を網羅しているかどうかは検査せず、どのケースにも当たらない値は何も追加しません。
  • パーセントで表す幅のように決まった候補のない値には、El::bind_style と El::bind_token が文字列からプロパティを設定します。この文字列は検査しません。これらはトークンと検査しない値で説明しています。

次に読むページ

トークンでは、いくつものスタイルが読む値に名前を付けます。シグナルを 1 回変えるだけで、たくさんの要素のスタイルを変えられます。